import { useState } from 'react'
import { createFileRoute, useParams } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { paymentMethodListOptions, paymentMethodMutations, paymentMethodKeys } from '@/api/payment-methods'
import { PaymentMethodForm } from '@/components/accounts/payment-method-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, Star, Search } from 'lucide-react'
import { toast } from 'sonner'
import type { PaymentMethod } from '@/types/account'

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

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

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

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

  const setDefaultMutation = useMutation({
    mutationFn: (id: string) => paymentMethodMutations.update(id, { isDefault: true }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: paymentMethodKeys.all(accountId) })
      toast.success('Default payment method updated')
    },
    onError: (err) => toast.error(err.message),
  })

  const deleteMutation = useMutation({
    mutationFn: paymentMethodMutations.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: paymentMethodKeys.all(accountId) })
      toast.success('Payment method removed')
    },
    onError: (err) => toast.error(err.message),
  })

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

  const columns: Column<PaymentMethod>[] = [
    {
      key: 'card_brand',
      header: 'Card',
      sortable: true,
      render: (m) => <span className="font-medium">{m.cardBrand ?? 'Card'} {m.lastFour ? `****${m.lastFour}` : ''}</span>,
    },
    {
      key: 'processor',
      header: 'Processor',
      sortable: true,
      render: (m) => <Badge variant="outline">{m.processor}</Badge>,
    },
    {
      key: 'expires',
      header: 'Expires',
      render: (m) => <>{m.expMonth && m.expYear ? `${m.expMonth}/${m.expYear}` : '-'}</>,
    },
    {
      key: 'status',
      header: 'Status',
      render: (m) => (
        <div className="flex gap-1">
          {m.isDefault && <Badge>Default</Badge>}
          {m.requiresUpdate && <Badge variant="destructive">Needs Update</Badge>}
        </div>
      ),
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (m) => (
        <div className="flex gap-1">
          {!m.isDefault && (
            <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); setDefaultMutation.mutate(m.id) }}>
              <Star className="h-4 w-4" />
            </Button>
          )}
          <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(m.id) }}>
            <Trash2 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">Payment Methods</h2>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button size="sm"><Plus className="mr-2 h-4 w-4" />Add Method</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Add Payment Method</DialogTitle></DialogHeader>
            <PaymentMethodForm 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 payment methods..."
            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>
  )
}
