import { useState } from 'react'
import { createFileRoute, useParams } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { taxExemptionListOptions, taxExemptionMutations, taxExemptionKeys } from '@/api/tax-exemptions'
import { TaxExemptionForm } from '@/components/accounts/tax-exemption-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, Check, X, Search } from 'lucide-react'
import { toast } from 'sonner'
import type { TaxExemption } from '@/types/account'

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

function statusBadge(status: string) {
  switch (status) {
    case 'approved': return <Badge className="bg-green-600">Approved</Badge>
    case 'pending': return <Badge variant="secondary">Pending</Badge>
    default: return <Badge variant="outline">None</Badge>
  }
}

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

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

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

  const approveMutation = useMutation({
    mutationFn: taxExemptionMutations.approve,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: taxExemptionKeys.all(accountId) })
      toast.success('Tax exemption approved')
    },
    onError: (err) => toast.error(err.message),
  })

  const revokeMutation = useMutation({
    mutationFn: (id: string) => {
      const reason = window.prompt('Reason for revoking this exemption:')
      if (!reason) throw new Error('Reason is required')
      return taxExemptionMutations.revoke(id, reason)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: taxExemptionKeys.all(accountId) })
      toast.success('Tax exemption revoked')
    },
    onError: (err) => toast.error(err.message),
  })

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

  const columns: Column<TaxExemption>[] = [
    {
      key: 'certificate_number',
      header: 'Certificate #',
      sortable: true,
      render: (e) => <span className="font-medium">{e.certificateNumber}</span>,
    },
    {
      key: 'type',
      header: 'Type',
      render: (e) => <>{e.certificateType ?? '-'}</>,
    },
    {
      key: 'state',
      header: 'State',
      render: (e) => <>{e.issuingState ?? '-'}</>,
    },
    {
      key: 'expires_at',
      header: 'Expires',
      sortable: true,
      render: (e) => <>{e.expiresAt ?? '-'}</>,
    },
    {
      key: 'status',
      header: 'Status',
      sortable: true,
      render: (e) => statusBadge(e.status),
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (e) => (
        <div className="flex gap-1">
          {e.status === 'pending' && (
            <Button variant="ghost" size="sm" onClick={(ev) => { ev.stopPropagation(); approveMutation.mutate(e.id) }}>
              <Check className="h-4 w-4 text-green-600" />
            </Button>
          )}
          {e.status === 'approved' && (
            <Button variant="ghost" size="sm" onClick={(ev) => { ev.stopPropagation(); revokeMutation.mutate(e.id) }}>
              <X className="h-4 w-4 text-destructive" />
            </Button>
          )}
        </div>
      ),
    },
  ]

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Tax Exemptions</h2>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button size="sm"><Plus className="mr-2 h-4 w-4" />Add Exemption</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Add Tax Exemption</DialogTitle></DialogHeader>
            <TaxExemptionForm 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 tax exemptions..."
            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>
  )
}
