import { useState } from 'react'
import { createFileRoute } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { supplierListOptions, supplierMutations, supplierKeys } from '@/api/inventory'
import { SupplierForm } from '@/components/inventory/supplier-form'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Search, Plus } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth.store'
import type { Supplier } from '@/types/inventory'

export const Route = createFileRoute('/_authenticated/inventory/suppliers/')({
  validateSearch: (search: Record<string, unknown>) => ({
    page: Number(search.page) || 1,
    limit: Number(search.limit) || 25,
    q: (search.q as string) || undefined,
    sort: (search.sort as string) || undefined,
    order: (search.order as 'asc' | 'desc') || 'asc',
  }),
  component: SuppliersPage,
})

function SuppliersPage() {
  const queryClient = useQueryClient()
  const hasPermission = useAuthStore((s) => s.hasPermission)
  const { params, setPage, setSearch, setSort } = usePagination()
  const [searchInput, setSearchInput] = useState(params.q ?? '')
  const [createOpen, setCreateOpen] = useState(false)
  const [editTarget, setEditTarget] = useState<Supplier | null>(null)

  const { data, isLoading } = useQuery(supplierListOptions(params))

  const createMutation = useMutation({
    mutationFn: supplierMutations.create,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: supplierKeys.all })
      toast.success('Supplier created')
      setCreateOpen(false)
    },
    onError: (err) => toast.error(err.message),
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) =>
      supplierMutations.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: supplierKeys.all })
      toast.success('Supplier updated')
      setEditTarget(null)
    },
    onError: (err) => toast.error(err.message),
  })

  const deleteMutation = useMutation({
    mutationFn: supplierMutations.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: supplierKeys.all })
      toast.success('Supplier deleted')
      setEditTarget(null)
    },
    onError: (err) => toast.error(err.message),
  })

  function handleSearchSubmit(e: React.FormEvent) {
    e.preventDefault()
    setSearch(searchInput)
  }

  const columns: Column<Supplier>[] = [
    {
      key: 'name',
      header: 'Name',
      sortable: true,
      render: (s) => <span className="font-medium">{s.name}</span>,
    },
    {
      key: 'contact_name',
      header: 'Contact',
      render: (s) => s.contactName ?? <span className="text-muted-foreground">—</span>,
    },
    {
      key: 'email',
      header: 'Email',
      sortable: true,
      render: (s) => s.email
        ? <a href={`mailto:${s.email}`} className="hover:underline" onClick={(e) => e.stopPropagation()}>{s.email}</a>
        : <span className="text-muted-foreground">—</span>,
    },
    {
      key: 'phone',
      header: 'Phone',
      render: (s) => s.phone ?? <span className="text-muted-foreground">—</span>,
    },
    {
      key: 'account_number',
      header: 'Account #',
      render: (s) => s.accountNumber
        ? <span className="font-mono text-sm">{s.accountNumber}</span>
        : <span className="text-muted-foreground">—</span>,
    },
    {
      key: 'payment_terms',
      header: 'Terms',
      render: (s) => s.paymentTerms ?? <span className="text-muted-foreground">—</span>,
    },
    {
      key: 'actions',
      header: '',
      render: (s) => hasPermission('inventory.edit') ? (
        <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); setEditTarget(s) }}>
          Edit
        </Button>
      ) : null,
    },
  ]

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Suppliers</h1>
        {hasPermission('inventory.edit') && (
          <Dialog open={createOpen} onOpenChange={setCreateOpen}>
            <DialogTrigger asChild>
              <Button><Plus className="mr-2 h-4 w-4" />New Supplier</Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader><DialogTitle>New Supplier</DialogTitle></DialogHeader>
              <SupplierForm
                onSubmit={(data) => { createMutation.mutate(data) }}
                loading={createMutation.isPending}
              />
            </DialogContent>
          </Dialog>
        )}
      </div>

      <form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search suppliers..."
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            className="pl-9"
          />
        </div>
        <Button type="submit" variant="secondary">Search</Button>
      </form>

      <DataTable
        columns={columns}
        data={data?.data ?? []}
        loading={isLoading}
        page={params.page}
        totalPages={data?.pagination.totalPages ?? 1}
        total={data?.pagination.total ?? 0}
        sort={params.sort}
        order={params.order}
        onPageChange={setPage}
        onSort={setSort}
        onRowClick={hasPermission('inventory.edit') ? setEditTarget : undefined}
      />

      {/* Edit dialog */}
      <Dialog open={!!editTarget} onOpenChange={(o) => !o && setEditTarget(null)}>
        <DialogContent>
          <DialogHeader><DialogTitle>Edit Supplier</DialogTitle></DialogHeader>
          {editTarget && (
            <SupplierForm
              defaultValues={editTarget}
              onSubmit={(data) => updateMutation.mutate({ id: editTarget.id, data })}
              loading={updateMutation.isPending}
              onDelete={hasPermission('inventory.admin') ? () => deleteMutation.mutate(editTarget.id) : undefined}
              deleteLoading={deleteMutation.isPending}
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
