'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Search,
  Filter,
  FileText,
  Send,
  CheckCircle2,
  Eye,
  Loader2,
  RefreshCcw,
  ChevronLeft,
  ChevronRight,
  DollarSign,
  AlertTriangle,
  TrendingUp,
  Hash,
} 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 {
  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 { useToast } from '@/hooks/use-toast'
import { api } from '@/lib/api'

interface Payment {
  id: string
  amount: number
  method: string
  transactionId: string
  status: string
  createdAt: string
}

interface Invoice {
  id: string
  invoiceNumber: string
  amount: number
  tax: number
  discount: number
  lateFee: number
  totalAmount: number
  paidAmount: number
  status: string
  dueDate: string
  createdAt: string
  notes: string
  user: { id: string; name: string; email: string; phone: string; area?: { id: string; name: string } | null }
  subscription: { id: string; plan: { id: string; name: string; price: number } }
  payments: Payment[]
}

interface InvoiceSummary {
  totalAmount: number
  totalPaid: number
  totalUnpaid: number
  totalInvoices: number
}

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',
  DUE: 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-400',
  PARTIAL: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-400',
}

const statusDotColors: Record<string, string> = {
  PAID: 'bg-emerald-500',
  UNPAID: 'bg-gray-400',
  DUE: 'bg-red-500',
  PARTIAL: 'bg-amber-500',
}

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',
  })
}

export default function InvoicesView() {
  const { toast } = useToast()
  const [invoices, setInvoices] = useState<Invoice[]>([])
  const [summary, setSummary] = useState<InvoiceSummary | null>(null)
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [statusFilter, setStatusFilter] = useState('all')
  const [searchQuery, setSearchQuery] = useState('')
  const [fromDate, setFromDate] = useState('')
  const [toDate, setToDate] = useState('')
  const [areaId, setAreaId] = useState('')
  const [areas, setAreas] = useState<{ id: string; name: string }[]>([])

  // Detail dialog
  const [selectedInvoice, setSelectedInvoice] = useState<Invoice | null>(null)
  const [detailOpen, setDetailOpen] = useState(false)
  const [markingPaid, setMarkingPaid] = useState(false)

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

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

      if (res.success) {
        setInvoices(res.data.invoices)
        setSummary(res.data.summary)
        setTotalPages(res.data.pagination.totalPages)
      }
    } catch {
      toast({ title: 'Error', description: 'Failed to load invoices', variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }, [page, statusFilter, fromDate, toDate, areaId, toast])

  const fetchAreas = useCallback(async () => {
    try {
      const res = await api.get<{ success: boolean; data: { areas: { id: string; name: string }[] } }>(
        '/api/areas?limit=50'
      )
      if (res.success) setAreas(res.data.areas)
    } catch {
      // silent fail for areas
    }
  }, [])

  useEffect(() => {
    fetchAreas()
  }, [fetchAreas])

  useEffect(() => {
    fetchInvoices()
  }, [fetchInvoices])

  const handleViewInvoice = async (invoice: Invoice) => {
    try {
      const res = await api.get<{ success: boolean; data: Invoice }>(`/api/invoices/${invoice.id}`)
      if (res.success) {
        setSelectedInvoice(res.data)
        setDetailOpen(true)
      }
    } catch {
      setSelectedInvoice(invoice)
      setDetailOpen(true)
    }
  }

  const handleMarkPaid = async () => {
    if (!selectedInvoice) return
    try {
      setMarkingPaid(true)
      const res = await api.post<{ success: boolean; message: string }>(
        `/api/invoices/${selectedInvoice.id}`,
        { action: 'mark_paid' }
      )
      if (res.success) {
        toast({ title: 'Success', description: res.message })
        setDetailOpen(false)
        fetchInvoices()
      }
    } catch {
      toast({ title: 'Error', description: 'Failed to mark invoice as paid', variant: 'destructive' })
    } finally {
      setMarkingPaid(false)
    }
  }

  const handleSendReminder = () => {
    toast({ title: 'Reminder Sent', description: `Reminder sent for invoice ${selectedInvoice?.invoiceNumber}` })
  }

  const filteredInvoices = searchQuery
    ? invoices.filter(
        (inv) =>
          inv.invoiceNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
          inv.user?.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          inv.user?.email.toLowerCase().includes(searchQuery.toLowerCase())
      )
    : invoices

  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">Invoices</h1>
          <p className="text-muted-foreground text-sm mt-1">
            Manage and track all invoices
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={fetchInvoices}>
          <RefreshCcw className="size-4" />
          <span className="hidden sm:inline">Refresh</span>
        </Button>
      </div>

      {/* Summary Cards */}
      {summary && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <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 Invoices</CardTitle>
              <div className="bg-sky-100 dark:bg-sky-900/30 rounded-full p-2">
                <FileText className="size-4 text-sky-600 dark:text-sky-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{summary.totalInvoices}</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">Total Amount</CardTitle>
              <div className="bg-purple-100 dark:bg-purple-900/30 rounded-full p-2">
                <Hash className="size-4 text-purple-600 dark:text-purple-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(summary.totalAmount)}</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">Collected</CardTitle>
              <div className="bg-emerald-100 dark:bg-emerald-900/30 rounded-full p-2">
                <TrendingUp className="size-4 text-emerald-600 dark:text-emerald-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(summary.totalPaid)}</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">Due Amount</CardTitle>
              <div className="bg-red-100 dark:bg-red-900/30 rounded-full p-2">
                <AlertTriangle className="size-4 text-red-600 dark:text-red-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(summary.totalUnpaid)}</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="Invoice #, client name..."
                  className="pl-9"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
            </div>

            <div className="w-full sm:w-[150px]">
              <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="UNPAID">Unpaid</SelectItem>
                  <SelectItem value="DUE">Due</SelectItem>
                  <SelectItem value="PARTIAL">Partial</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 className="w-full sm:w-[150px]">
              <Label className="text-xs mb-1.5 block">Area</Label>
              <Select value={areaId} onValueChange={(v) => { setAreaId(v === '__all__' ? '' : v); setPage(1) }}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="All Areas" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="__all__">All Areas</SelectItem>
                  {areas.map((area) => (
                    <SelectItem key={area.id} value={area.id}>
                      {area.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Invoices Table */}
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Invoice #</TableHead>
                  <TableHead>Client Name</TableHead>
                  <TableHead className="text-right">Amount</TableHead>
                  <TableHead className="text-right">Tax</TableHead>
                  <TableHead className="text-right">Discount</TableHead>
                  <TableHead className="text-right">Total</TableHead>
                  <TableHead>Due Date</TableHead>
                  <TableHead>Status</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>
                  ))
                ) : filteredInvoices.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center py-12 text-muted-foreground">
                      <FileText className="size-10 mx-auto mb-2 opacity-40" />
                      <p>No invoices found</p>
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredInvoices.map((invoice) => (
                    <TableRow key={invoice.id}>
                      <TableCell className="font-mono text-xs font-medium">
                        {invoice.invoiceNumber}
                      </TableCell>
                      <TableCell>
                        <div>
                          <div className="font-medium">{invoice.user?.name || 'Unknown'}</div>
                          <div className="text-xs text-muted-foreground">
                            {invoice.user?.area?.name || ''}
                          </div>
                        </div>
                      </TableCell>
                      <TableCell className="text-right">{formatCurrency(invoice.amount)}</TableCell>
                      <TableCell className="text-right">{formatCurrency(invoice.tax)}</TableCell>
                      <TableCell className="text-right">
                        {invoice.discount > 0 ? (
                          <span className="text-emerald-600">-{formatCurrency(invoice.discount)}</span>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right font-semibold">
                        {formatCurrency(invoice.totalAmount)}
                      </TableCell>
                      <TableCell>{formatDate(invoice.dueDate)}</TableCell>
                      <TableCell>
                        <Badge variant="secondary" className={statusColors[invoice.status] || ''}>
                          <span className={`mr-1 inline-block size-1.5 rounded-full ${statusDotColors[invoice.status] || ''}`} />
                          {invoice.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleViewInvoice(invoice)}
                        >
                          <Eye className="size-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
        {/* Pagination */}
        {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>

      {/* Invoice Detail Dialog */}
      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
          {selectedInvoice && (
            <>
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  <FileText className="size-5" />
                  Invoice Details
                </DialogTitle>
                <DialogDescription>
                  {selectedInvoice.invoiceNumber}
                </DialogDescription>
              </DialogHeader>

              <div className="space-y-6">
                {/* Status & Actions */}
                <div className="flex flex-wrap items-center gap-2">
                  <Badge
                    variant="secondary"
                    className={statusColors[selectedInvoice.status] || ''}
                  >
                    <span className={`mr-1 inline-block size-1.5 rounded-full ${statusDotColors[selectedInvoice.status] || ''}`} />
                    {selectedInvoice.status}
                  </Badge>
                  <span className="text-sm text-muted-foreground">
                    Created: {formatDate(selectedInvoice.createdAt)}
                  </span>
                </div>

                {/* Client Info */}
                <div>
                  <h3 className="text-sm font-semibold mb-2">Client Information</h3>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm">
                    <div>
                      <span className="text-muted-foreground">Name:</span>{' '}
                      <span className="font-medium">{selectedInvoice.user?.name}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">Email:</span>{' '}
                      <span className="font-medium">{selectedInvoice.user?.email}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">Phone:</span>{' '}
                      <span className="font-medium">{selectedInvoice.user?.phone || 'N/A'}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">Area:</span>{' '}
                      <span className="font-medium">{selectedInvoice.user?.area?.name || 'N/A'}</span>
                    </div>
                  </div>
                </div>

                <Separator />

                {/* Invoice Amounts */}
                <div>
                  <h3 className="text-sm font-semibold mb-2">Invoice Details</h3>
                  <div className="rounded-lg border p-4 space-y-2">
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Plan</span>
                      <span className="font-medium">{selectedInvoice.subscription?.plan?.name}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Base Amount</span>
                      <span>{formatCurrency(selectedInvoice.amount)}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Tax</span>
                      <span>{formatCurrency(selectedInvoice.tax)}</span>
                    </div>
                    {selectedInvoice.discount > 0 && (
                      <div className="flex justify-between text-sm text-emerald-600">
                        <span>Discount</span>
                        <span>-{formatCurrency(selectedInvoice.discount)}</span>
                      </div>
                    )}
                    {selectedInvoice.lateFee > 0 && (
                      <div className="flex justify-between text-sm text-red-600">
                        <span>Late Fee</span>
                        <span>+{formatCurrency(selectedInvoice.lateFee)}</span>
                      </div>
                    )}
                    <Separator />
                    <div className="flex justify-between font-semibold">
                      <span>Total</span>
                      <span>{formatCurrency(selectedInvoice.totalAmount)}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Paid</span>
                      <span className="text-emerald-600 font-medium">
                        {formatCurrency(selectedInvoice.paidAmount)}
                      </span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Due Date</span>
                      <span>{formatDate(selectedInvoice.dueDate)}</span>
                    </div>
                    {selectedInvoice.paidAmount < selectedInvoice.totalAmount && (
                      <div className="flex justify-between text-sm font-semibold text-red-600">
                        <span>Balance Due</span>
                        <span>
                          {formatCurrency(selectedInvoice.totalAmount - selectedInvoice.paidAmount)}
                        </span>
                      </div>
                    )}
                  </div>
                </div>

                {/* Payment History */}
                <div>
                  <h3 className="text-sm font-semibold mb-2">Payment History</h3>
                  {selectedInvoice.payments && selectedInvoice.payments.length > 0 ? (
                    <div className="space-y-2">
                      {selectedInvoice.payments.map((payment) => (
                        <div
                          key={payment.id}
                          className="flex items-center justify-between rounded-lg border p-3 text-sm"
                        >
                          <div className="flex items-center gap-3">
                            <div className="bg-emerald-100 dark:bg-emerald-900/30 rounded-full p-1.5">
                              <DollarSign className="size-3.5 text-emerald-600 dark:text-emerald-400" />
                            </div>
                            <div>
                              <div className="font-medium">{formatCurrency(payment.amount)}</div>
                              <div className="text-xs text-muted-foreground">
                                {payment.method} {payment.transactionId ? `• ${payment.transactionId}` : ''}
                              </div>
                            </div>
                          </div>
                          <div className="text-right">
                            <div className="font-medium">{payment.status}</div>
                            <div className="text-xs text-muted-foreground">
                              {formatDate(payment.createdAt)}
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <p className="text-sm text-muted-foreground py-4 text-center">
                      No payments recorded yet
                    </p>
                  )}
                </div>
              </div>

              <DialogFooter className="flex-col gap-2 sm:flex-row">
                <Button variant="outline" size="sm" onClick={handleSendReminder}>
                  <Send className="size-4" />
                  Send Reminder
                </Button>
                {selectedInvoice.status !== 'PAID' && (
                  <Button size="sm" onClick={handleMarkPaid} disabled={markingPaid}>
                    {markingPaid ? (
                      <Loader2 className="size-4 animate-spin" />
                    ) : (
                      <CheckCircle2 className="size-4" />
                    )}
                    Mark as Paid
                  </Button>
                )}
              </DialogFooter>
            </>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
