
'use client';

import { useState, useMemo } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, TableFooter } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { type Supplier, type PurchaseOrder, type SupplierPayment } from '@/lib/types';
import { format } from 'date-fns';
import { ar } from 'date-fns/locale';
import { Check, ChevronsUpDown, Share2, ChevronDown, ChevronUp, Printer } from 'lucide-react';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { Input } from '../ui/input';
import { formatCurrency } from '@/lib/currency-formatter';

type StatementTransaction = {
    type: 'order' | 'payment';
    id: string;
    date: Date;
    description: string;
    debit: number;
    credit: number;
    balance: number;
    details?: any;
    amount: number;
};

type SupplierStatementProps = {
    suppliers: Supplier[];
    orders: PurchaseOrder[];
    payments: SupplierPayment[];
    t: any;
    tGlobal: any;
    locale: string;
    currencySymbol?: string;
}

export default function SupplierStatement({ suppliers, orders, payments, t, tGlobal, locale, currencySymbol = '$' }: SupplierStatementProps) {
    const [selectedSupplierId, setSelectedSupplierId] = useState('');
    const [popoverOpen, setPopoverOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState("");
    const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());

    const filteredSuppliers = useMemo(() => {
        if (!searchTerm) return suppliers;
        return suppliers.filter(s => s.name.toLowerCase().includes(searchTerm.toLowerCase()));
    }, [suppliers, searchTerm]);

    const selectedSupplier = useMemo(() => {
        return suppliers.find(s => s.id === selectedSupplierId);
    }, [selectedSupplierId, suppliers]);

    const statementData = useMemo(() => {
        if (!selectedSupplierId || !selectedSupplier) return null;

        const supplierOrders = orders.filter(ord => ord.supplierId === selectedSupplierId);
        const supplierPayments = payments.filter(p => p.supplierId === selectedSupplierId);

        const allTx: StatementTransaction[] = [
            ...supplierOrders.map(ord => ({
                type: 'order' as const,
                id: ord.id,
                date: new Date(ord.date),
                description: (t.orderDescription ?? 'Purchase Order #{id}').replace('{id}', ord.orderNumber || ord.id.slice(-6)),
                amount: ord.grandTotal,
                debit: ord.grandTotal,
                credit: 0,
                balance: 0,
                details: ord,
            })),
            ...supplierPayments.map(p => ({
                type: 'payment' as const,
                id: p.id,
                date: new Date(p.date),
                description: t.paymentDescription ?? 'Payment',
                        amount: p.amountBase ?? p.amount,
                        debit: 0,
                        credit: p.amountBase ?? p.amount,
                balance: 0,
                details: p,
            })),
        ].sort((a, b) => a.date.getTime() - b.date.getTime());

        let openingBalance = selectedSupplier.balance;
        for (let i = allTx.length - 1; i >= 0; i--) {
            const tx = allTx[i];
            if (tx.type === 'order') {
                openingBalance -= tx.amount;
            } else {
                openingBalance += tx.amount;
            }
        }

        let runningBalance = openingBalance;
        for (const tx of allTx) {
            if (tx.type === 'order') {
                runningBalance += tx.amount;
            } else {
                runningBalance -= tx.amount;
            }
            tx.balance = runningBalance;
        }

        return { transactions: allTx, openingBalance, finalBalance: runningBalance };
    }, [selectedSupplierId, selectedSupplier, orders, payments, t]);

    const toggleRow = (id: string) => {
        const newExpanded = new Set(expandedRows);
        if (newExpanded.has(id)) {
            newExpanded.delete(id);
        } else {
            newExpanded.add(id);
        }
        setExpandedRows(newExpanded);
    };

    const handleShare = () => {
        if (!statementData || !selectedSupplier) return;

        const header = `${t.accountStatementTitle ?? 'Supplier Account Statement'} - ${selectedSupplier.name}\n`;
        const date = `${t.date ?? 'Date'}: ${format(new Date(), 'yyyy-MM-dd')}\n\n`;
        const separator = '═══════════════════════════════════════\n';

        const openingRow = `${t.openingBalance ?? 'Opening Balance'}: ${formatCurrency(statementData.openingBalance, currencySymbol)}\n${separator}`;

        const transactionDetails = statementData.transactions.map(row => {
            let detail = `\n${format(row.date, 'yyyy-MM-dd')} | ${row.description}\n`;
            detail += `${t.debit ?? 'Debit'}: ${formatCurrency(row.debit, currencySymbol)} | ${t.credit ?? 'Credit'}: ${formatCurrency(row.credit, currencySymbol)} | ${t.balance ?? 'Balance'}: ${formatCurrency(row.balance, currencySymbol)}\n`;

            if (row.type === 'order' && row.details && row.details.items) {
                detail += `  ${t.items ?? 'Items'}:\n`;
                row.details.items.forEach((item: any) => {
                    detail += `    - ${item.name}: ${item.quantity} × ${formatCurrency(item.unitPrice, currencySymbol)} = ${formatCurrency(item.total, currencySymbol)}\n`;
                });
                detail += `  ${t.subTotal ?? 'Subtotal'}: ${formatCurrency(row.details.subTotal, currencySymbol)}\n`;
                detail += `  ${t.grandTotal ?? 'Grand Total'}: ${formatCurrency(row.details.grandTotal, currencySymbol)}\n`;
                detail += `  ${t.amountPaid ?? 'Amount Paid'}: ${formatCurrency(row.details.amountPaid, currencySymbol)}\n`;
                detail += `  ${t.amountDue ?? 'Amount Due'}: ${formatCurrency(row.details.amountDue, currencySymbol)}\n`;
            }

            return detail;
        }).join('\n');

        const footer = `\n${separator}${t.finalBalance ?? 'Final Balance'}: ${formatCurrency(statementData.finalBalance, currencySymbol)}\n`;

        const fullText = header + date + separator + openingRow + transactionDetails + footer;
        const encodedText = encodeURIComponent(fullText);
        window.open(`https://wa.me/?text=${encodedText}`);
    };

    const handlePrint = () => {
        if (!statementData || !selectedSupplier) return;

        const printWindow = window.open('', '', 'height=600,width=900');
        if (!printWindow) return;

        let htmlContent = `
        <html dir="rtl">
        <head>
            <title>${t.accountStatementTitle ?? 'Supplier Account Statement'}</title>
            <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body { font-family: Arial, sans-serif; padding: 20px; direction: rtl; }
                .header { text-align: center; margin-bottom: 20px; }
                .header h1 { font-size: 20px; margin-bottom: 10px; }
                .header p { color: #666; margin: 5px 0; }
                table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                th, td { padding: 8px; border: 1px solid #ddd; text-align: right; }
                th { background-color: #f5f5f5; font-weight: bold; }
                .debit { color: #d32f2f; }
                .credit { color: #388e3c; }
                .summary { margin: 20px 0; }
                .summary-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #ddd; }
                .summary-row.total { font-weight: bold; font-size: 16px; }
                .details-table { margin-left: 20px; font-size: 12px; }
                .page-break { page-break-after: always; }
                @media print { body { margin: 0; padding: 10px; } }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>${t.accountStatementTitle ?? 'Supplier Account Statement'}</h1>
                <p><strong>${t.supplierName ?? 'Supplier Name'}:</strong> ${selectedSupplier.name}</p>
                <p><strong>${t.date ?? 'Date'}:</strong> ${format(new Date(), 'PPP')}</p>
            </div>

            <table>
                <thead>
                    <tr>
                        <th>${t.date ?? 'Date'}</th>
                        <th>${t.statementDescriptionCol ?? 'Description'}</th>
                        <th>${t.debit ?? 'Debit'}</th>
                        <th>${t.credit ?? 'Credit'}</th>
                        <th>${t.balance ?? 'Balance'}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr style="background-color: #f9f9f9;">
                        <td colspan="4"><strong>${t.openingBalance ?? 'Opening Balance'}</strong></td>
                        <td><strong>${currencySymbol}${statementData.openingBalance.toFixed(2)}</strong></td>
                    </tr>
                    ${statementData.transactions.map((row) => {
                        let rowHtml = `
                        <tr>
                            <td>${format(row.date, 'yyyy-MM-dd')}</td>
                            <td>${row.description}</td>
                            <td class="debit">${row.debit > 0 ? currencySymbol + row.debit.toFixed(2) : '-'}</td>
                            <td class="credit">${row.credit > 0 ? currencySymbol + row.credit.toFixed(2) : '-'}</td>
                            <td><strong>${currencySymbol}${row.balance.toFixed(2)}</strong></td>
                        </tr>`;

                        if (row.type === 'order' && row.details && row.details.items) {
                            rowHtml += `
                            <tr style="background-color: #f5f5f5;">
                                <td colspan="5">
                                    <table class="details-table" style="width: 100%;">
                                        <thead>
                                            <tr>
                                                <th>${t.item ?? 'Item'}</th>
                                                <th>${t.quantity ?? 'Qty'}</th>
                                                <th>${t.price ?? 'Price'}</th>
                                                <th>${t.total ?? 'Total'}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            ${row.details.items.map((item: any) => `
                                            <tr>
                                                <td>${item.name}</td>
                                                <td>${item.quantity}</td>
                                                <td>${currencySymbol}${item.unitPrice.toFixed(2)}</td>
                                                <td>${currencySymbol}${item.total.toFixed(2)}</td>
                                            </tr>`).join('')}
                                        </tbody>
                                    </table>
                                    <div style="margin-top: 10px;">
                                        <div class="summary-row"><span>${t.subTotal ?? 'Subtotal'}:</span> <span>${currencySymbol}${row.details.subTotal.toFixed(2)}</span></div>
                                        <div class="summary-row"><span>${t.grandTotal ?? 'Grand Total'}:</span> <span>${currencySymbol}${row.details.grandTotal.toFixed(2)}</span></div>
                                        <div class="summary-row"><span>${t.amountPaid ?? 'Amount Paid'}:</span> <span>${currencySymbol}${row.details.amountPaid.toFixed(2)}</span></div>
                                        <div class="summary-row total"><span>${t.amountDue ?? 'Amount Due'}:</span> <span style="color: ${row.details.amountDue > 0 ? '#d32f2f' : '#388e3c'};">${currencySymbol}${row.details.amountDue.toFixed(2)}</span></div>
                                    </div>
                                </td>
                            </tr>`;
                        }

                        return rowHtml;
                    }).join('')}
                    <tr style="background-color: #f0f0f0; font-weight: bold; font-size: 14px;">
                        <td colspan="4">${t.finalBalance ?? 'Final Balance'}</td>
                        <td>${currencySymbol}${statementData.finalBalance.toFixed(2)}</td>
                    </tr>
                </tbody>
            </table>

            <script>
                window.print();
                window.close();
            </script>
        </body>
        </html>`;

        printWindow.document.write(htmlContent);
        printWindow.document.close();
    };

    return (
        <Card>
            <CardHeader>
                <CardTitle>{t.accountStatementTitle ?? 'Supplier Account Statement'}</CardTitle>
                <CardDescription>{t.accountStatementDescription ?? 'Select a supplier to view their detailed statement.'}</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
                    <PopoverTrigger asChild>
                        <Button
                            variant="outline"
                            role="combobox"
                            aria-expanded={popoverOpen}
                            className="w-full justify-between md:w-1/2"
                        >
                            {selectedSupplierId
                                ? suppliers.find((supplier) => supplier.id === selectedSupplierId)?.name
                                : (t.selectSupplier ?? 'Select a supplier...')}
                            <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[--radix-popover-trigger-width] p-0">
                        <div className="p-2">
                            <Input
                                placeholder={t.searchSupplier ?? 'Search supplier...'}
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                autoFocus
                            />
                        </div>
                        <div className="max-h-60 overflow-y-auto">
                            {filteredSuppliers.length === 0 ? (
                                <div className="p-2 text-center text-sm text-muted-foreground">
                                    {t.noSuppliersFound ?? 'No suppliers found.'}
                                </div>
                            ) : (
                                filteredSuppliers.map((supplier) => (
                                    <div
                                        key={supplier.id}
                                        onClick={() => {
                                            setSelectedSupplierId(supplier.id);
                                            setPopoverOpen(false);
                                            setSearchTerm('');
                                        }}
                                        className={cn(
                                            "relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent hover:bg-accent",
                                        )}
                                        data-selected={supplier.id === selectedSupplierId}
                                    >
                                        <Check
                                            className={cn(
                                                "me-2 h-4 w-4",
                                                selectedSupplierId === supplier.id ? "opacity-100" : "opacity-0"
                                            )}
                                        />
                                        {supplier.name}
                                    </div>
                                ))
                            )}
                        </div>
                    </PopoverContent>
                </Popover>

                {selectedSupplier && (
                    <div>
                        {statementData ? (
                            <>
                                <div className="overflow-x-auto">
                                    <Table>
                                        <TableHeader>
                                            <TableRow>
                                                <TableHead className="w-8"></TableHead>
                                                <TableHead className="text-start">{t.date ?? 'Date'}</TableHead>
                                                <TableHead className="text-start">{t.statementDescriptionCol ?? 'Description'}</TableHead>
                                                <TableHead className="text-end">{t.debit ?? 'Debit'}</TableHead>
                                                <TableHead className="text-end">{t.credit ?? 'Credit'}</TableHead>
                                                <TableHead className="text-end">{t.balance ?? 'Balance'}</TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            <TableRow>
                                                <TableCell></TableCell>
                                                <TableCell colSpan={3} className="font-bold text-start">{t.openingBalance ?? 'Opening Balance'}</TableCell>
                                                <TableCell className="text-end font-bold">{formatCurrency(statementData.openingBalance, currencySymbol)}</TableCell>
                                            </TableRow>
                                            {statementData.transactions.length === 0 ? (
                                                <TableRow>
                                                    <TableCell colSpan={6} className="text-center h-24 text-muted-foreground">{t.noTransactions ?? 'No transactions found for this period.'}</TableCell>
                                                </TableRow>
                                            ) : (
                                                statementData.transactions.map((row) => (
                                                    <tbody key={row.id}>
                                                        <TableRow className="hover:bg-muted/50 cursor-pointer" onClick={() => toggleRow(row.id)}>
                                                            <TableCell className="text-center">
                                                                {row.type === 'order' && (
                                                                    expandedRows.has(row.id) ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />
                                                                )}
                                                            </TableCell>
                                                            <TableCell className="text-start">{format(row.date, 'PPP', { locale: locale === 'ar' ? ar : undefined })}</TableCell>
                                                            <TableCell className="text-start">{row.description}</TableCell>
                                                            <TableCell className="text-end text-red-600">{row.debit > 0 ? `${formatCurrency(row.debit, currencySymbol)}` : '-'}</TableCell>
                                                            <TableCell className="text-end text-green-600">{row.credit > 0 ? `${formatCurrency(row.credit, currencySymbol)}` : '-'}</TableCell>
                                                            <TableCell className="text-end font-medium">{formatCurrency(row.balance, currencySymbol)}</TableCell>
                                                        </TableRow>
                                                        {expandedRows.has(row.id) && row.type === 'order' && row.details && (
                                                            <TableRow className="bg-muted/30">
                                                                <TableCell colSpan={6}>
                                                                    <div className="p-4 space-y-4">
                                                                        {row.details.items && row.details.items.length > 0 && (
                                                                            <div>
                                                                                <h4 className="font-semibold mb-2 text-sm">{t?.items ?? 'Items'}</h4>
                                                                                <Table className="text-xs">
                                                                                    <TableHeader>
                                                                                        <TableRow>
                                                                                            <TableHead>{t?.item ?? 'Item'}</TableHead>
                                                                                            <TableHead className="text-center">{t?.quantity ?? 'Qty'}</TableHead>
                                                                                            <TableHead className="text-end">{t?.price ?? 'Price'}</TableHead>
                                                                                            <TableHead className="text-end">{t?.total ?? 'Total'}</TableHead>
                                                                                        </TableRow>
                                                                                    </TableHeader>
                                                                                    <TableBody>
                                                                                        {row.details.items.map((item: any, idx: number) => (
                                                                                            <TableRow key={idx}>
                                                                                                <TableCell>{item.name}</TableCell>
                                                                                                <TableCell className="text-center">{item.quantity}</TableCell>
                                                                                            <TableCell className="text-end">{formatCurrency(item.unitPrice, currencySymbol)}</TableCell>
                                                                                            <TableCell className="text-end">{formatCurrency(item.total, currencySymbol)}</TableCell>
                                                                                            </TableRow>
                                                                                        ))}
                                                                                    </TableBody>
                                                                                </Table>
                                                                            </div>
                                                                        )}
                                                                        <div className="border-t pt-2">
                                                                            <div className="flex justify-between text-sm">
                                                                                <span>{t?.subTotal ?? 'Subtotal'}:</span>
                                                                                <span>{formatCurrency(row.details.subTotal, currencySymbol)}</span>
                                                                            </div>
                                                                            <div className="flex justify-between text-sm font-semibold">
                                                                                <span>{t?.grandTotal ?? 'Grand Total'}:</span>
                                                                                <span>{formatCurrency(row.details.grandTotal, currencySymbol)}</span>
                                                                            </div>
                                                                            <div className="flex justify-between text-sm">
                                                                                <span>{t?.amountPaid ?? 'Amount Paid'}:</span>
                                                                                <span>{formatCurrency(row.details.amountPaid, currencySymbol)}</span>
                                                                            </div>
                                                                            <div className="flex justify-between text-sm font-semibold text-red-600">
                                                                                <span>{t?.amountDue ?? 'Amount Due'}:</span>
                                                                                <span>{formatCurrency(row.details.amountDue, currencySymbol)}</span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </TableCell>
                                                            </TableRow>
                                                        )}
                                                    </tbody>
                                                ))
                                            )}
                                        </TableBody>
                                        <TableFooter>
                                            <TableRow className="bg-muted/50">
                                                <TableCell></TableCell>
                                                <TableCell colSpan={3} className="text-end font-extrabold text-lg">{t.finalBalance ?? 'Final Balance'}</TableCell>
                                                <TableCell className="text-end font-extrabold text-lg">{formatCurrency(statementData.finalBalance, currencySymbol)}</TableCell>
                                            </TableRow>
                                        </TableFooter>
                                    </Table>
                                </div>
                            </>
                        ) : (
                            <div className="text-center text-muted-foreground py-8">
                                {t.noTransactions ?? 'No transactions found for this period.'}
                            </div>
                        )}
                        <div className="flex justify-end gap-2 mt-4">
                            <Button onClick={handlePrint} variant="outline">
                                <Printer className="me-2 h-4 w-4" />
                                {t.print ?? 'Print'}
                            </Button>
                            <Button onClick={handleShare}>
                                <Share2 className="me-2 h-4 w-4" />
                                {t.shareOnWhatsApp ?? 'Share on WhatsApp'}
                            </Button>
                        </div>
                    </div>
                )}
            </CardContent>
        </Card>
    );
}
