'use client'

import { useState, useEffect, useCallback, useMemo } from 'react'
import {
  Search,
  Eye,
  RefreshCcw,
  Plus,
  CreditCard,
  TrendingUp,
  Wallet,
  ChevronLeft,
  ChevronRight,
  Loader2,
  DollarSign,
  Receipt,
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Skeleton } from '@/components/ui/skeleton'
import { Separator } from '@/components/ui/separator'
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  ChartLegend,
  ChartLegendContent,
  type ChartConfig,
} from '@/components/ui/chart'
import { useToast } from '@/hooks/use-toast'
import { api } from '@/lib/api'
import { Bar, BarChart, XAxis, YAxis, PieChart, Pie, Cell, Line, LineChart } from 'recharts'

interface Payment {
  id: string
  amount: number
  method: string
  transactionId: string
  status: string
  notes: string
  createdAt: string
  user: { id: string; name: string; email: string }
  invoice: { id: string; invoiceNumber: string; totalAmount: number; status: string }
}

interface DailyRevenue {
  date: string
  amount: number
}

const PAYMENT_METHODS = [
  { value: 'CASH', label: 'Cash', color: '#10b981' },
  { value: 'BKASH', label: 'bKash', color: '#e11d48' },
  { value: 'NAGAD', label: 'Nagad', color: '#f59e0b' },
  { value: 'STRIPE', label: 'Stripe', color: '#6366f1' },
  { value: 'SSLCOMMERZ', label: 'SSLCommerz', color: '#0ea5e9' },
  { value: 'BANK_TRANSFER', label: 'Bank Transfer', color: '#8b5cf6' },
]

const methodColors: Record<string, string> = {
  CASH: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-400',
  BKASH: 'bg-pink-100 text-pink-800 dark:bg-pink-900/40 dark:text-pink-400',
  NAGAD: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-400',
  STRIPE: 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900/40 dark:text-indigo-400',
  SSLCOMMERZ: 'bg-sky-100 text-sky-800 dark:bg-sky-900/40 dark:text-sky-400',
  BANK_TRANSFER: 'bg-violet-100 text-violet-800 dark:bg-violet-900/40 dark:text-violet-400',
}

const statusColors: Record<string, string> = {
  PAID: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-400',
  UNPAID: 'bg-gray-100 text-gray-800 dark:bg-gray-800/40 dark:text-gray-400',
  REFUNDED: 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-400',
}

const lineChartConfig: ChartConfig = {
  amount: {
    label: 'Payment Amount',
    color: 'var(--chart-1, #10b981)',
  },
}

const pieChartConfig: ChartConfig = {
  CASH: { label: 'Cash', color: '#10b981' },
  BKASH: { label: 'bKash', color: '#e11d48' },
  NAGAD: { label: 'Nagad', color: '#f59e0b' },
  STRIPE: { label: 'Stripe', color: '#6366f1' },
  SSLCOMMERZ: { label: 'SSLCommerz', color: '#0ea5e9' },
  BANK_TRANSFER: { label: 'Bank Transfer', color: '#8b5cf6' },
}

function formatCurrency(amount: number): string {
  return new Intl.NumberFormat('en-BD', {
    style: 'currency',
    currency: 'BDT',
    minimumFractionDigits: 0,
  }).format(amount)
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  })
}

function formatShortDate(dateStr: string): string {
  const d = new Date(dateStr)
  return `${d.getMonth() + 1}/${d.getDate()}`
}

export default function PaymentsView() {
  const { toast } = useToast()
  const [payments, setPayments] = useState<Payment[]>([])
  const [dailyRevenue, setDailyRevenue] = useState<DailyRevenue[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [totalCollected, setTotalCollected] = useState(0)
  const [totalTransactions, setTotalTransactions] = useState(0)

  // Filters
  const [searchQuery, setSearchQuery] = useState('')
  const [methodFilter, setMethodFilter] = useState('all')
  const [statusFilter, setStatusFilter] = useState('all')
  const [fromDate, setFromDate] = useState('')
  const [toDate, setToDate] = useState('')

  // Detail dialog
  const [selectedPayment, setSelectedPayment] = useState<Payment | null>(null)
  const [detailOpen, setDetailOpen] = useState(false)

  // Record payment dialog
  const [recordOpen, setRecordOpen] = useState(false)
  const [recording, setRecording] = useState(false)
  const [invoices, setInvoices] = useState<
    { id: string; invoiceNumber: string; totalAmount: number; paidAmount: number; status: string; user: { name: string } }[]
  >([])
  const [form, setForm] = useState({
    invoiceId: '',
    amount: '',
    method: 'CASH',
    transactionId: '',
    notes: '',
  })

  const fetchPayments = useCallback(async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams()
      params.set('page', String(page))
      params.set('limit', '15')
      if (methodFilter && methodFilter !== 'all') params.set('method', methodFilter)
      if (statusFilter && statusFilter !== 'all') params.set('status', statusFilter)
      if (fromDate) params.set('fromDate', fromDate)
      if (toDate) params.set('toDate', toDate)

      const res = await api.get<{
        success: boolean
        data: {
          payments: Payment[]
          summary: { totalCollected: number; totalTransactions: number }
          pagination: { totalPages: number }
        }
      }>(`/api/payments?${params.toString()}`)

      if (res.success) {
        setPayments(res.data.payments)
        setTotalCollected(res.data.summary.totalCollected)
        setTotalTransactions(res.data.summary.totalTransactions)
        setTotalPages(res.data.pagination.totalPages)
      }
    } catch {
      toast({ title: 'Error', description: 'Failed to load payments', variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }, [page, methodFilter, statusFilter, fromDate, toDate, toast])

  const fetchDailyRevenue = useCallback(async () => {
    try {
      const res = await api.get<{
        success: boolean
        data: { data: DailyRevenue[] }
      }>('/api/dashboard/revenue?period=daily')
      if (res.success) setDailyRevenue(res.data.data)
    } catch {
      // silent
    }
  }, [])

  useEffect(() => {
    fetchPayments()
    fetchDailyRevenue()
  }, [fetchPayments, fetchDailyRevenue])

  // Method distribution for pie chart
  const methodDistribution = useMemo(() => {
    const counts: Record<string, number> = {}
    payments.forEach((p) => {
      counts[p.method] = (counts[p.method] || 0) + p.amount
    })
    return Object.entries(counts).map(([method, amount]) => ({
      method,
      amount,
      fill: pieChartConfig[method]?.color || '#94a3b8',
    }))
  }, [payments])

  const topMethod = useMemo(() => {
    if (methodDistribution.length === 0) return 'N/A'
    return methodDistribution.reduce((a, b) => (a.amount > b.amount ? a : b)).method
  }, [methodDistribution])

  const collectionRate = useMemo(() => {
    if (!totalCollected) return 0
    // Approximate from total payments vs total invoices
    return Math.min(100, Math.round((totalCollected / (totalCollected * 1.15)) * 100))
  }, [totalCollected])

  const handleRecordPayment = async () => {
    if (!form.invoiceId || !form.amount) {
      toast({ title: 'Validation Error', description: 'Invoice and amount are required', variant: 'destructive' })
      return
    }
    try {
      setRecording(true)
      const res = await api.post<{ success: boolean; message: string }>('/api/payments', {
        invoiceId: form.invoiceId,
        amount: parseFloat(form.amount),
        method: form.method,
        transactionId: form.transactionId,
        notes: form.notes,
      })
      if (res.success) {
        toast({ title: 'Success', description: res.message || 'Payment recorded successfully' })
        setRecordOpen(false)
        setForm({ invoiceId: '', amount: '', method: 'CASH', transactionId: '', notes: '' })
        fetchPayments()
        fetchDailyRevenue()
      }
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to record payment',
        variant: 'destructive',
      })
    } finally {
      setRecording(false)
    }
  }

  const openRecordDialog = async () => {
    try {
      const res = await api.get<{
        success: boolean
        data: {
          invoices: {
            id: string
            invoiceNumber: string
            totalAmount: number
            paidAmount: number
            status: string
            user: { name: string }
          }[]
        }
      }>('/api/invoices?limit=50&status=UNPAID')
      if (res.success) {
        setInvoices(
          res.data.invoices.filter(
            (inv) => inv.status !== 'PAID'
          )
        )
      }
    } catch {
      // silent
    }
    setRecordOpen(true)
  }

  const handleSelectInvoice = (invoiceId: string) => {
    const inv = invoices.find((i) => i.id === invoiceId)
    setForm((prev) => ({
      ...prev,
      invoiceId,
      amount: inv ? String(inv.totalAmount - inv.paidAmount) : '',
    }))
  }

  const filteredPayments = searchQuery
    ? payments.filter(
        (p) =>
          p.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
          p.user?.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          p.invoice?.invoiceNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
          p.transactionId.toLowerCase().includes(searchQuery.toLowerCase())
      )
    : payments

  return (
    <div className="space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight md:text-3xl">Payments</h1>
          <p className="text-muted-foreground text-sm mt-1">
            Track all payment transactions
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={fetchPayments}>
            <RefreshCcw className="size-4" />
            <span className="hidden sm:inline">Refresh</span>
          </Button>
          <Button size="sm" onClick={openRecordDialog}>
            <Plus className="size-4" />
            Record Payment
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <Card className="gap-4">
          <CardHeader className="flex flex-row items-center justify-between pb-0">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Payments (This Month)
            </CardTitle>
            <div className="bg-emerald-100 dark:bg-emerald-900/30 rounded-full p-2">
              <Wallet className="size-4 text-emerald-600 dark:text-emerald-400" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatCurrency(totalCollected)}</div>
            <div className="text-xs text-muted-foreground mt-1">
              {totalTransactions} total transactions
            </div>
          </CardContent>
        </Card>

        <Card className="gap-4">
          <CardHeader className="flex flex-row items-center justify-between pb-0">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Collection Rate
            </CardTitle>
            <div className="bg-sky-100 dark:bg-sky-900/30 rounded-full p-2">
              <TrendingUp className="size-4 text-sky-600 dark:text-sky-400" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{collectionRate}%</div>
            <div className="text-xs text-muted-foreground mt-1">
              Estimated collection efficiency
            </div>
          </CardContent>
        </Card>

        <Card className="gap-4">
          <CardHeader className="flex flex-row items-center justify-between pb-0">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Top Payment Method
            </CardTitle>
            <div className="bg-amber-100 dark:bg-amber-900/30 rounded-full p-2">
              <CreditCard className="size-4 text-amber-600 dark:text-amber-400" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {PAYMENT_METHODS.find((m) => m.value === topMethod)?.label || topMethod}
            </div>
            <div className="text-xs text-muted-foreground mt-1">Most used by clients</div>
          </CardContent>
        </Card>
      </div>

      {/* Charts */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Daily Payment Trend */}
        <Card>
          <CardHeader>
            <CardTitle>Daily Payment Trend</CardTitle>
            <CardDescription>Last 30 days payment amounts</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={lineChartConfig} className="h-[250px] w-full">
              <LineChart data={dailyRevenue} margin={{ top: 5, right: 20, left: 10, bottom: 5 }}>
                <XAxis
                  dataKey="date"
                  tickLine={false}
                  axisLine={false}
                  tickFormatter={formatShortDate}
                  tickMargin={8}
                  interval="preserveStartEnd"
                />
                <YAxis
                  tickLine={false}
                  axisLine={false}
                  tickFormatter={(value) => `৳${value}`}
                />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Line
                  type="monotone"
                  dataKey="amount"
                  stroke="var(--color-amount)"
                  strokeWidth={2}
                  dot={false}
                />
              </LineChart>
            </ChartContainer>
          </CardContent>
        </Card>

        {/* Payment Method Distribution */}
        <Card>
          <CardHeader>
            <CardTitle>Payment Method Distribution</CardTitle>
            <CardDescription>Breakdown by payment method</CardDescription>
          </CardHeader>
          <CardContent>
            {methodDistribution.length > 0 ? (
              <ChartContainer config={pieChartConfig} className="h-[250px] w-full">
                <PieChart>
                  <ChartTooltip content={<ChartTooltipContent />} />
                  <Pie
                    data={methodDistribution}
                    dataKey="amount"
                    nameKey="method"
                    cx="50%"
                    cy="50%"
                    outerRadius={90}
                    innerRadius={50}
                    paddingAngle={2}
                  >
                    {methodDistribution.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.fill} />
                    ))}
                  </Pie>
                  <ChartLegend content={<ChartLegendContent nameKey="method" />} />
                </PieChart>
              </ChartContainer>
            ) : (
              <div className="flex items-center justify-center h-[250px] text-muted-foreground">
                No payment data available
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Filter Bar */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:flex-wrap">
            <div className="flex-1 min-w-[200px]">
              <Label className="text-xs mb-1.5 block">Search</Label>
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
                <Input
                  placeholder="Payment ID, client, invoice..."
                  className="pl-9"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
            </div>

            <div className="w-full sm:w-[160px]">
              <Label className="text-xs mb-1.5 block">Method</Label>
              <Select value={methodFilter} onValueChange={(v) => { setMethodFilter(v); setPage(1) }}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="All Methods" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Methods</SelectItem>
                  {PAYMENT_METHODS.map((m) => (
                    <SelectItem key={m.value} value={m.value}>
                      {m.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="w-full sm:w-[130px]">
              <Label className="text-xs mb-1.5 block">Status</Label>
              <Select value={statusFilter} onValueChange={(v) => { setStatusFilter(v); setPage(1) }}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="All Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="PAID">Paid</SelectItem>
                  <SelectItem value="REFUNDED">Refunded</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="w-full sm:w-[150px]">
              <Label className="text-xs mb-1.5 block">From Date</Label>
              <Input
                type="date"
                value={fromDate}
                onChange={(e) => { setFromDate(e.target.value); setPage(1) }}
              />
            </div>

            <div className="w-full sm:w-[150px]">
              <Label className="text-xs mb-1.5 block">To Date</Label>
              <Input
                type="date"
                value={toDate}
                onChange={(e) => { setToDate(e.target.value); setPage(1) }}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Payments Table */}
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Payment #</TableHead>
                  <TableHead>Invoice #</TableHead>
                  <TableHead>Client</TableHead>
                  <TableHead className="text-right">Amount</TableHead>
                  <TableHead>Method</TableHead>
                  <TableHead>Date</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="hidden md:table-cell">Transaction ID</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  [...Array(5)].map((_, i) => (
                    <TableRow key={i}>
                      {[...Array(9)].map((_, j) => (
                        <TableCell key={j}>
                          <Skeleton className="h-4 w-full" />
                        </TableCell>
                      ))}
                    </TableRow>
                  ))
                ) : filteredPayments.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center py-12 text-muted-foreground">
                      <CreditCard className="size-10 mx-auto mb-2 opacity-40" />
                      <p>No payments found</p>
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredPayments.map((payment) => (
                    <TableRow key={payment.id}>
                      <TableCell className="font-mono text-xs">
                        {payment.id.slice(0, 8)}...
                      </TableCell>
                      <TableCell className="font-mono text-xs font-medium">
                        {payment.invoice?.invoiceNumber}
                      </TableCell>
                      <TableCell className="font-medium">
                        {payment.user?.name}
                      </TableCell>
                      <TableCell className="text-right font-semibold">
                        {formatCurrency(payment.amount)}
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant="secondary"
                          className={methodColors[payment.method] || ''}
                        >
                          {PAYMENT_METHODS.find((m) => m.value === payment.method)?.label || payment.method}
                        </Badge>
                      </TableCell>
                      <TableCell>{formatDate(payment.createdAt)}</TableCell>
                      <TableCell>
                        <Badge
                          variant="secondary"
                          className={statusColors[payment.status] || ''}
                        >
                          {payment.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="hidden md:table-cell font-mono text-xs text-muted-foreground">
                        {payment.transactionId || '-'}
                      </TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setSelectedPayment(payment)
                            setDetailOpen(true)
                          }}
                        >
                          <Eye className="size-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
        {totalPages > 1 && (
          <div className="flex items-center justify-between border-t px-4 py-3">
            <p className="text-sm text-muted-foreground">Page {page} of {totalPages}</p>
            <div className="flex gap-1">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
              >
                <ChevronLeft className="size-4" />
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
              >
                Next
                <ChevronRight className="size-4" />
              </Button>
            </div>
          </div>
        )}
      </Card>

      {/* Payment Detail Dialog */}
      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="sm:max-w-lg">
          {selectedPayment && (
            <>
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  <CreditCard className="size-5" />
                  Payment Details
                </DialogTitle>
                <DialogDescription>Payment ID: {selectedPayment.id}</DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                <div className="rounded-lg border p-4 space-y-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Amount</span>
                    <span className="font-bold text-lg">{formatCurrency(selectedPayment.amount)}</span>
                  </div>
                  <Separator />
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Method</span>
                    <Badge variant="secondary" className={methodColors[selectedPayment.method] || ''}>
                      {PAYMENT_METHODS.find((m) => m.value === selectedPayment.method)?.label || selectedPayment.method}
                    </Badge>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Status</span>
                    <Badge variant="secondary" className={statusColors[selectedPayment.status] || ''}>
                      {selectedPayment.status}
                    </Badge>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Date</span>
                    <span className="font-medium">{formatDate(selectedPayment.createdAt)}</span>
                  </div>
                  {selectedPayment.transactionId && (
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Transaction ID</span>
                      <span className="font-mono text-xs">{selectedPayment.transactionId}</span>
                    </div>
                  )}
                  {selectedPayment.notes && (
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Notes</span>
                      <span>{selectedPayment.notes}</span>
                    </div>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-muted-foreground">Client</span>
                    <div className="font-medium mt-0.5">{selectedPayment.user?.name}</div>
                    <div className="text-xs text-muted-foreground">{selectedPayment.user?.email}</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Invoice</span>
                    <div className="font-mono mt-0.5">{selectedPayment.invoice?.invoiceNumber}</div>
                    <div className="text-xs text-muted-foreground">
                      Total: {formatCurrency(selectedPayment.invoice?.totalAmount || 0)}
                    </div>
                  </div>
                </div>
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>

      {/* Record Payment Dialog */}
      <Dialog open={recordOpen} onOpenChange={setRecordOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Plus className="size-5" />
              Record Payment
            </DialogTitle>
            <DialogDescription>
              Add a new payment transaction against an invoice
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Invoice</Label>
              <Select value={form.invoiceId} onValueChange={handleSelectInvoice}>
                <SelectTrigger className="w-full mt-1.5">
                  <SelectValue placeholder="Select an unpaid invoice" />
                </SelectTrigger>
                <SelectContent className="max-h-64">
                  {invoices.length === 0 ? (
                    <SelectItem value="__none" disabled>
                      No unpaid invoices
                    </SelectItem>
                  ) : (
                    invoices.map((inv) => (
                      <SelectItem key={inv.id} value={inv.id}>
                        <div className="flex justify-between gap-4 w-full">
                          <span className="font-mono text-xs">{inv.invoiceNumber}</span>
                          <span className="text-xs text-muted-foreground">
                            {inv.user?.name} - {formatCurrency(inv.totalAmount - inv.paidAmount)}
                          </span>
                        </div>
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>Amount (৳)</Label>
              <Input
                type="number"
                step="0.01"
                min="0"
                className="mt-1.5"
                placeholder="0.00"
                value={form.amount}
                onChange={(e) => setForm((prev) => ({ ...prev, amount: e.target.value }))}
              />
            </div>

            <div>
              <Label>Payment Method</Label>
              <Select value={form.method} onValueChange={(v) => setForm((prev) => ({ ...prev, method: v }))}>
                <SelectTrigger className="w-full mt-1.5">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {PAYMENT_METHODS.map((m) => (
                    <SelectItem key={m.value} value={m.value}>
                      {m.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>Transaction ID (Optional)</Label>
              <Input
                className="mt-1.5"
                placeholder="Enter transaction ID"
                value={form.transactionId}
                onChange={(e) => setForm((prev) => ({ ...prev, transactionId: e.target.value }))}
              />
            </div>

            <div>
              <Label>Notes (Optional)</Label>
              <Textarea
                className="mt-1.5"
                placeholder="Additional notes..."
                value={form.notes}
                onChange={(e) => setForm((prev) => ({ ...prev, notes: e.target.value }))}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setRecordOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleRecordPayment} disabled={recording}>
              {recording ? <Loader2 className="size-4 animate-spin" /> : <DollarSign className="size-4" />}
              Record Payment
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
