import { useState } from 'react'
import { createFileRoute, useParams } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { processorLinkListOptions, processorLinkMutations, processorLinkKeys } from '@/api/processor-links'
import { ProcessorLinkForm } from '@/components/accounts/processor-link-form'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Plus, Trash2, Search } from 'lucide-react'
import { toast } from 'sonner'
import type { ProcessorLink } from '@/types/account'

export const Route = createFileRoute('/_authenticated/accounts/$accountId/processor-links')({
  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: ProcessorLinksTab,
})

function ProcessorLinksTab() {
  const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/processor-links' })
  const queryClient = useQueryClient()
  const [dialogOpen, setDialogOpen] = useState(false)
  const { params, setPage, setSearch, setSort } = usePagination()
  const [searchInput, setSearchInput] = useState(params.q ?? '')

  const { data, isLoading } = useQuery(processorLinkListOptions(accountId, params))

  const createMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => processorLinkMutations.create(accountId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: processorLinkKeys.all(accountId) })
      toast.success('Processor link added')
      setDialogOpen(false)
    },
    onError: (err) => toast.error(err.message),
  })

  const deleteMutation = useMutation({
    mutationFn: processorLinkMutations.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: processorLinkKeys.all(accountId) })
      toast.success('Processor link removed')
    },
    onError: (err) => toast.error(err.message),
  })

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

  const columns: Column<ProcessorLink>[] = [
    {
      key: 'processor',
      header: 'Processor',
      sortable: true,
      render: (l) => <Badge variant="outline">{l.processor}</Badge>,
    },
    {
      key: 'customer_id',
      header: 'Customer ID',
      render: (l) => <span className="font-mono text-sm">{l.processorCustomerId}</span>,
    },
    {
      key: 'status',
      header: 'Status',
      render: (l) => l.isActive ? <Badge>Active</Badge> : <Badge variant="secondary">Inactive</Badge>,
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (l) => (
        <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(l.id) }}>
          <Trash2 className="h-4 w-4 text-destructive" />
        </Button>
      ),
    },
  ]

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Processor Links</h2>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button size="sm"><Plus className="mr-2 h-4 w-4" />Add Link</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Add Processor Link</DialogTitle></DialogHeader>
            <ProcessorLinkForm accountId={accountId} onSubmit={createMutation.mutate} 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 processor links..."
            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}
      />
    </div>
  )
}
