'use client';

import { useState } from 'react';
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { type SalesInvoice } from "@/lib/types";
import { format } from "date-fns";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Pencil, Search } from "lucide-react";
import EditInvoiceDialog from "./edit-invoice-dialog";
import { formatCurrency } from "@/lib/currency-formatter";

type SalesInvoiceListProps = {
  invoices: SalesInvoice[];
  customers: any[];
  materials: any[];
  onRefresh?: () => void;
  t: any;
  currencySymbol?: string;
};

export default function SalesInvoiceList({ invoices, customers, materials, onRefresh, t, currencySymbol = '$' }: SalesInvoiceListProps) {
  const [selectedInvoice, setSelectedInvoice] = useState<SalesInvoice | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  // Filter invoices based on search query
  const filteredInvoices = invoices.filter((invoice) => {
    if (!searchQuery) return true;
    
    const query = searchQuery.toLowerCase();
    return (
      (invoice.invoiceNumber || '').toLowerCase().includes(query) ||
      (invoice.customerName || '').toLowerCase().includes(query) ||
      (invoice.grandTotal?.toString() || '').includes(query) ||
      (invoice.amountDue?.toString() || '').includes(query)
    );
  });

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>{t?.pastInvoicesTitle ?? 'فواتير المبيعات السابقة'}</CardTitle>
          <CardDescription>{t?.pastInvoicesDescription ?? 'مراجعة الفواتير التي تم إنشاؤها مسبقاً.'}</CardDescription>
          <div className="relative mt-4">
            <Search className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              type="text"
              placeholder={t?.searchPlaceholder ?? 'ابحث برقم الفاتورة، اسم الزبون، أو المبلغ...'}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pr-10"
            />
          </div>
        </CardHeader>
        <CardContent>
          {filteredInvoices.length === 0 ? (
            <p className="text-center text-muted-foreground py-12">
              {searchQuery ? (t?.noSearchResults ?? 'لا توجد نتائج للبحث.') : (t?.noInvoicesFound ?? 'لم يتم العثور على فواتير.')}
            </p>
          ) : (
            <Accordion type="single" collapsible className="w-full">
              {filteredInvoices.map((invoice) => (
                <AccordionItem value={invoice.id} key={invoice.id}>
                  <AccordionTrigger>
                    <div className="flex justify-between items-center w-full pe-4">
                      <div className="flex flex-col text-start">
                          <span className="font-bold text-lg">{invoice.invoiceNumber}</span>
                          <span className="text-sm text-muted-foreground">{invoice.customerName}</span>
                          <span className="text-xs text-muted-foreground">{format(new Date(invoice.date), "PPP")}</span>
                      </div>
                      <div className="flex flex-col text-end">
                          <span className="font-mono text-lg font-bold">{formatCurrency(invoice.grandTotal, currencySymbol)}</span>
                         <Badge variant={invoice.status === 'cancelled' ? 'secondary' : invoice.amountDue > 0 ? "destructive" : "secondary"} className={invoice.status === 'cancelled' ? 'bg-gray-200 text-gray-700' : invoice.amountDue === 0 ? 'bg-green-100 text-green-800' : ''}>
                            {invoice.status === 'cancelled' ? (t?.cancelled ?? 'ملغي') : invoice.amountDue > 0 ? `${t?.due ?? 'متبقي'}: ${formatCurrency(invoice.amountDue, currencySymbol)}` : t?.paid ?? 'مدفوع'}
                          </Badge>
                      </div>
                    </div>
                  </AccordionTrigger>
                  <AccordionContent>
                    <div className="space-y-4">
                      <div className="p-4 bg-muted/50 rounded-md">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="text-start">{t?.item ?? 'الصنف'}</TableHead>
                                    <TableHead className="text-center">{t?.quantity ?? 'الكمية'}</TableHead>
                                    <TableHead className="text-center">{t?.price ?? 'السعر'}</TableHead>
                                    <TableHead className="text-center">{t?.bonus ?? 'بونص'}</TableHead>
                                    <TableHead className="text-end">{t?.total ?? 'الإجمالي'}</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {invoice.items.map((item, index) => (
                                    <TableRow key={index}>
                                        <TableCell className="text-start">{item.name || item.materialId}</TableCell>
                                        <TableCell className="text-center">{item.quantity}</TableCell>
                                        <TableCell className="text-center font-mono">{formatCurrency(item.unitPrice, currencySymbol)}</TableCell>
                                        <TableCell className="text-center font-mono text-green-600">+{item.bonus}</TableCell>
                                        <TableCell className="text-end font-mono">{formatCurrency(item.total, currencySymbol)}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                            <TableFooter>
                                <TableRow>
                                    <TableCell colSpan={4} className="text-end font-bold">{t?.subTotal ?? 'المجموع الفرعي'}</TableCell>
                                    <TableCell className="text-end font-bold font-mono">{formatCurrency(invoice.subTotal, currencySymbol)}</TableCell>
                                </TableRow>
                                 <TableRow>
                                    <TableCell colSpan={4} className="text-end font-bold">{t?.amountPaid ?? 'المبلغ المدفوع'}</TableCell>
                                    <TableCell className="text-end font-bold font-mono">{formatCurrency(invoice.amountPaid, currencySymbol)}</TableCell>
                                </TableRow>
                                 <TableRow>
                                    <TableCell colSpan={4} className="text-end font-bold text-lg">{t?.amountDue ?? 'المبلغ المتبقي'}</TableCell>
                                    <TableCell className="text-end font-bold font-mono text-lg">{formatCurrency(invoice.amountDue, currencySymbol)}</TableCell>
                                </TableRow>
                            </TableFooter>
                        </Table>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            setSelectedInvoice(invoice);
                            setIsDialogOpen(true);
                          }}
                        >
                          <Pencil className="h-4 w-4 mr-2" />
                          {t?.edit ?? 'تعديل'}
                        </Button>
                      </div>
                    </div>
                  </AccordionContent>
                </AccordionItem>
              ))}
            </Accordion>
          )}
        </CardContent>
      </Card>

      <EditInvoiceDialog
        invoice={selectedInvoice}
        customers={customers}
        materials={materials}
        open={isDialogOpen}
        onOpenChange={setIsDialogOpen}
        onSuccess={() => {
          onRefresh?.();
        }}
        t={t}
        currencySymbol={currencySymbol}
      />
    </>
  );
}
