"use client"

import { useState, useEffect } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Search, Eye, Download, Printer, Send, ChevronLeft, ChevronRight, Pencil, ShieldCheck, Lock, Check } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { formatDate, formatCurrency } from "@/lib/utils"
import { SortableHeader } from "@/components/SortableHeader"

type InvoiceWithClient = {
  id: string
  invoiceNumber: string
  clientId: string | null
  client: { name: string; phone: string } | null
  total: any
  discount: any
  paidAmount: any
  paymentMethod: string | null
  status: string
  seller?: { id: string; name: string } | null
  lastPaymentSeller?: { id: string; name: string } | null
  createdAt: Date
}

type InvoicesTableProps = {
  invoices: InvoiceWithClient[]
  total: number
  page: number
  totalPages: number
}

export default function InvoicesTable({ invoices, total, page, totalPages }: InvoicesTableProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [searchQuery, setSearchQuery] = useState(searchParams.get('search') || '')
  const [statusFilter, setStatusFilter] = useState(searchParams.get('status') || 'all')
  const [paymentMethod, setPaymentMethod] = useState(searchParams.get('payment') || 'all')
  const [viewInvoice, setViewInvoice] = useState<InvoiceWithClient | null>(null)
  const [editInvoice, setEditInvoice] = useState<InvoiceWithClient | null>(null)
  const [additionalPayment, setAdditionalPayment] = useState("")
  const [updating, setUpdating] = useState(false)
  
  // PIN/Seller state
  type Seller = { id: string; name: string }
  const [sellers, setSellers] = useState<Seller[]>([])
  const [showPinDialog, setShowPinDialog] = useState(false)
  const [selectedSeller, setSelectedSeller] = useState("")
  const [pin, setPin] = useState("")
  const [verifyingPin, setVerifyingPin] = useState(false)

  useEffect(() => {
    fetch('/api/sellers').then(r => r.json()).then(setSellers).catch(() => {})
  }, [])

  useEffect(() => {
    const timer = setTimeout(() => {
      const params = new URLSearchParams()
      if (searchQuery) params.set('search', searchQuery)
      if (statusFilter !== 'all') params.set('status', statusFilter)
      if (paymentMethod !== 'all') params.set('payment', paymentMethod)
      params.set('page', '1')
      router.push(`?${params.toString()}`)
    }, 500)
    return () => clearTimeout(timer)
  }, [searchQuery, statusFilter, paymentMethod, router])

  const handlePageChange = (newPage: number) => {
    const params = new URLSearchParams()
    const search = searchParams.get('search')
    const status = searchParams.get('status')
    const payment = searchParams.get('payment')
    if (search) params.set('search', search)
    if (status) params.set('status', status)
    if (payment) params.set('payment', payment)
    params.set('page', String(newPage))
    router.push(`?${params.toString()}`)
  }

  const handleUpdatePayment = async () => {
    if (!editInvoice || !additionalPayment) return
    
    const amount = parseFloat(additionalPayment)
    if (isNaN(amount) || amount <= 0) return

    // Show PIN dialog first
    setShowPinDialog(true)
  }

  const validatePinAndUpdate = async () => {
    if (!editInvoice || !selectedSeller || !pin) return

    setVerifyingPin(true)
    try {
      const verifyRes = await fetch('/api/sellers/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sellerId: selectedSeller, pin }),
      })

      if (!verifyRes.ok) {
        const err = await verifyRes.json()
        alert(err.error || 'PIN invalide')
        return
      }

      // PIN OK → apply the payment
      setVerifyingPin(false)
      setShowPinDialog(false)
      setPin("")
      setUpdating(true)
      try {
        const amount = parseFloat(additionalPayment)
        const currentPaid = Number(editInvoice.paidAmount)
        const newPaid = Math.min(currentPaid + amount, Number(editInvoice.total))
        const newStatus = newPaid >= Number(editInvoice.total) ? 'PAID' : 'PENDING'

        const response = await fetch(`/api/invoices/${editInvoice.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ paidAmount: newPaid, status: newStatus, sellerId: selectedSeller }),
        })

        if (response.ok) {
          setEditInvoice(null)
          setAdditionalPayment("")
          setSelectedSeller("")
          router.refresh()
        } else {
          const error = await response.json()
          alert(error.error || 'Failed to update payment')
        }
      } catch (error) {
        console.error('Error updating payment:', error)
        alert('Failed to update payment')
      } finally {
        setUpdating(false)
      }
    } catch (error) {
      console.error('Error verifying PIN:', error)
      alert('Erreur de vérification')
    } finally {
      setVerifyingPin(false)
    }
  }

  return (
    <>
      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input 
            placeholder="Rechercher une facture..." 
            className="pl-10"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Statut" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Tous</SelectItem>
            <SelectItem value="PAID">Payée</SelectItem>
            <SelectItem value="PENDING">En attente</SelectItem>
            <SelectItem value="CANCELLED">Annulée</SelectItem>
          </SelectContent>
        </Select>
        <Select value={paymentMethod} onValueChange={setPaymentMethod}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Mode de paiement" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Tous</SelectItem>
            <SelectItem value="Espèces">Espèces</SelectItem>
            <SelectItem value="Carte">Carte</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="rounded-lg border">
        <Table>
          <TableHeader>
            <TableRow>
              <SortableHeader column="invoiceNumber" label="N° Facture" />
              <SortableHeader column="client.name" label="Client" />
              <SortableHeader column="seller.name" label="Vendeur" />
              <SortableHeader column="createdAt" label="Date" />
              <TableHead>Mode de paiement</TableHead>
              <SortableHeader column="discount" label="Remise" className="text-right" />
              <SortableHeader column="total" label="Total" className="text-right" />
              <SortableHeader column="status" label="Statut" />
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {invoices.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                  Aucune facture trouvée
                </TableCell>
              </TableRow>
            ) : (
              invoices.map((invoice) => (
                <TableRow key={invoice.id}>
                  <TableCell className="font-medium">{invoice.invoiceNumber}</TableCell>
                  <TableCell>{invoice.client?.name || '-'}</TableCell>
                  <TableCell>
                    <Badge variant="outline" className="font-normal border-slate-200">
                      {invoice.seller?.name || '-'}
                    </Badge>
                  </TableCell>
                  <TableCell>{formatDate(invoice.createdAt.toString())}</TableCell>
                  <TableCell>{invoice.paymentMethod || '-'}</TableCell>
                  <TableCell className="text-right text-red-600">{Number(invoice.discount) > 0 ? `-${formatCurrency(Number(invoice.discount))}` : '-'}</TableCell>
                  <TableCell className="text-right font-medium">{formatCurrency(Number(invoice.total))}</TableCell>
                  <TableCell>
                    {invoice.status === 'PENDING' ? (
                      <div className="text-sm">
                        <div className="text-muted-foreground">Payé: {formatCurrency(Number(invoice.paidAmount))}</div>
                        <div className="text-amber-600">Reste: {formatCurrency(Number(invoice.total) - Number(invoice.paidAmount))}</div>
                      </div>
                    ) : (
                      <Badge variant="success">Payée</Badge>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-1">
                      <Button variant="ghost" size="icon" onClick={() => setViewInvoice(invoice)}>
                        <Eye className="h-4 w-4" />
                      </Button>
                      {invoice.status === 'PENDING' && (
                        <Button variant="ghost" size="icon" onClick={() => {
                          setEditInvoice(invoice)
                          if (invoice.seller) {
                            setSelectedSeller(invoice.seller.id)
                          }
                        }}>
                          <Pencil className="h-4 w-4" />
                        </Button>
                      )}
                      <Button variant="ghost" size="icon" onClick={() => window.open(`/api/invoices/${invoice.id}/pdf`, '_blank')}>
                        <Download className="h-4 w-4" />
                      </Button>
                      <Button variant="ghost" size="icon" onClick={() => {
                          const printWindow = window.open(`/api/invoices/${invoice.id}/pdf`, '_blank')
                          printWindow?.addEventListener('load', () => {
                            printWindow.print()
                          })
                        }}>
                        <Printer className="h-4 w-4" />
                      </Button>
                      <Button 
                        variant="ghost" 
                        size="icon"
                        onClick={() => {
                          if (invoice.client?.phone) {
                            const phone = invoice.client.phone.replace(/\D/g, '')
                            const waUrl = `https://wa.me/${phone}`
                            window.open(waUrl, '_blank')
                          }
                        }}
                        disabled={!invoice.client?.phone}
                      >
                        <Send className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-between px-2 py-4">
          <div className="text-sm text-muted-foreground">
            Affichage de {((page - 1) * 10) + 1} à {Math.min(page * 10, total)} sur {total} résultats
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={page <= 1}
              onClick={() => handlePageChange(page - 1)}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="text-sm">Page {page} sur {totalPages}</span>
            <Button
              variant="outline"
              size="sm"
              disabled={page >= totalPages}
              onClick={() => handlePageChange(page + 1)}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      <Dialog open={!!viewInvoice} onOpenChange={(open) => !open && setViewInvoice(null)}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>Détails de la facture</DialogTitle>
          </DialogHeader>
          {viewInvoice && (
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground text-sm">N° Facture</Label>
                  <p className="font-medium">{viewInvoice.invoiceNumber}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground text-sm">Client</Label>
                  <p className="font-medium">{viewInvoice.client?.name || '-'}</p>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground text-sm">Vendeur</Label>
                  <p className="font-medium">{viewInvoice.seller?.name || '-'}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground text-sm">Date</Label>
                  <p className="font-medium">{formatDate(viewInvoice.createdAt.toString())}</p>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground text-sm">Total</Label>
                  <p className="font-medium text-lg text-teal-600">{formatCurrency(Number(viewInvoice.total))}</p>
                </div>
                {Number(viewInvoice.discount) > 0 && (
                  <div>
                    <Label className="text-muted-foreground text-sm">Remise</Label>
                    <p className="font-medium text-red-600">-{formatCurrency(Number(viewInvoice.discount))}</p>
                  </div>
                )}
                <div>
                  <Label className="text-muted-foreground text-sm">Statut</Label>
                  <Badge
                    variant={
                      viewInvoice.status === "PAID" ? "success" :
                      viewInvoice.status === "PENDING" ? "warning" : "destructive"
                    }
                  >
                    {viewInvoice.status === "PAID" ? "Payée" :
                     viewInvoice.status === "PENDING" ? "En attente" : "Annulée"}
                  </Badge>
                </div>
              </div>
              {viewInvoice.status === 'PENDING' && (
                <div className="grid grid-cols-2 gap-4 pt-2 border-t">
                  <div>
                    <Label className="text-muted-foreground text-sm">Montant payé</Label>
                    <p className="font-medium text-green-600">{formatCurrency(Number(viewInvoice.paidAmount))}</p>
                  </div>
                  <div>
                    <Label className="text-muted-foreground text-sm">Reste à payer</Label>
                    <p className="font-medium text-amber-600">{formatCurrency(Number(viewInvoice.total) - Number(viewInvoice.paidAmount))}</p>
                  </div>
                </div>
              )}
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setViewInvoice(null)}>Fermer</Button>
            {viewInvoice && (
              <Button variant="outline" onClick={() => window.open(`/api/invoices/${viewInvoice.id}/pdf`, '_blank')}>
                <Download className="mr-2 h-4 w-4" />
                Télécharger PDF
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={!!editInvoice} onOpenChange={(open) => { if (!open) { setEditInvoice(null); setAdditionalPayment("") } }}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>Ajouter un paiement</DialogTitle>
            <DialogDescription>
              Facture {editInvoice?.invoiceNumber}
            </DialogDescription>
          </DialogHeader>
          {editInvoice && (() => {
            const remaining = Number(editInvoice.total) - Number(editInvoice.paidAmount)
            const parsed = parseFloat(additionalPayment) || 0
            const isOverMax = parsed > remaining
            return (
              <div className="space-y-4 py-4">
                {selectedSeller && (
                  <div className="bg-teal-50 border border-teal-200 rounded-md px-3 py-2 text-sm flex items-center gap-2">
                    <span className="text-teal-700 font-medium">Vendeur:</span>
                    <span className="text-teal-800 font-bold">{sellers.find(s => s.id === selectedSeller)?.name}</span>
                  </div>
                )}
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <Label className="text-muted-foreground">Total facture</Label>
                    <p className="font-medium">{formatCurrency(Number(editInvoice.total))}</p>
                  </div>
                  {Number(editInvoice.discount) > 0 && (
                    <div>
                      <Label className="text-muted-foreground">Remise</Label>
                      <p className="font-medium text-red-600">-{formatCurrency(Number(editInvoice.discount))}</p>
                    </div>
                  )}
                  <div>
                    <Label className="text-muted-foreground">Déjà payé</Label>
                    <p className="font-medium text-green-600">{formatCurrency(Number(editInvoice.paidAmount))}</p>
                  </div>
                </div>
                <div className="bg-amber-50 border border-amber-200 rounded-md px-3 py-2 text-amber-700 font-semibold text-sm">
                  Restant à payer : {formatCurrency(remaining)}
                </div>
                <div className="grid gap-2">
                  <Label>Montant à ajouter</Label>
                  <Input
                    type="number"
                    placeholder={`Max ${formatCurrency(remaining)}`}
                    value={additionalPayment}
                    min={0.01}
                    max={remaining}
                    onChange={(e) => {
                      const val = parseFloat(e.target.value)
                      if (!isNaN(val) && val > remaining) {
                        setAdditionalPayment(String(remaining))
                      } else {
                        setAdditionalPayment(e.target.value)
                      }
                    }}
                    className={isOverMax ? 'border-red-500' : ''}
                  />
                  {isOverMax && (
                    <p className="text-xs text-red-500">Le montant ne peut pas dépasser le restant ({formatCurrency(remaining)})</p>
                  )}
                </div>
              </div>
            )
          })()}
          <DialogFooter>
            <Button variant="outline" onClick={() => { setEditInvoice(null); setAdditionalPayment("") }}>Annuler</Button>
            <Button
              className="bg-teal-600 hover:bg-teal-700"
              onClick={handleUpdatePayment}
              disabled={updating || !additionalPayment || parseFloat(additionalPayment) <= 0 || parseFloat(additionalPayment) > (Number(editInvoice?.total) - Number(editInvoice?.paidAmount))}
            >
              {updating ? 'Mise à jour...' : 'Ajouter le paiement'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* PIN Verification Dialog */}
      <Dialog open={showPinDialog} onOpenChange={(open) => { if (!open) { setShowPinDialog(false); setPin("") } }}>
        <DialogContent className="sm:max-w-[380px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ShieldCheck className="h-5 w-5 text-teal-600" />
              Validation Vendeur
            </DialogTitle>
            <DialogDescription>
              Saisissez votre code PIN pour valider ce paiement.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label>Vendeur</Label>
              <Select value={selectedSeller} onValueChange={setSelectedSeller}>
                <SelectTrigger>
                  <SelectValue placeholder="Choisir un vendeur" />
                </SelectTrigger>
                <SelectContent>
                  {sellers.map(s => (
                    <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label>Code PIN</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  type="password"
                  placeholder="****"
                  className="pl-10 text-center text-2xl tracking-[1em]"
                  maxLength={6}
                  value={pin}
                  onChange={(e) => setPin(e.target.value)}
                  autoFocus
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => { setShowPinDialog(false); setPin("") }} disabled={verifyingPin}>
              Annuler
            </Button>
            <Button
              className="bg-teal-600 hover:bg-teal-700"
              onClick={validatePinAndUpdate}
              disabled={!selectedSeller || pin.length < 4 || verifyingPin}
            >
              {verifyingPin ? 'Validation...' : (
                <><Check className="mr-2 h-4 w-4" />Confirmer</>  
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
