
'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 Customer, type SalesInvoice, type CustomerPayment } 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: 'invoice' | 'payment';
    id: string;
    date: Date;
    description: string;
    amount: number;
    debit: number;
    credit: number;
    balance: number;
    details?: any;
};

type CustomerStatementProps = {
    customers: Customer[];
    invoices: SalesInvoice[];
    payments: CustomerPayment[];
    t: any;
    tGlobal: any;
    locale: string;
    currencySymbol?: string;
}

export default function CustomerStatement({ customers, invoices, payments, t, tGlobal, locale, currencySymbol = '$' }: CustomerStatementProps) {
    const [selectedCustomerId, setSelectedCustomerId] = useState('');
    const [popoverOpen, setPopoverOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState("");
    const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());

    const filteredCustomers = useMemo(() => {
        if (!searchTerm) return customers;
        return customers.filter(c => c.name.toLowerCase().includes(searchTerm.toLowerCase()));
    }, [customers, searchTerm]);

    const selectedCustomer = useMemo(() => {
        return customers.find(c => c.id === selectedCustomerId);
    }, [selectedCustomerId, customers]);

    const statementData = useMemo(() => {
        if (!selectedCustomerId || !selectedCustomer) return null;

        const customerInvoices = invoices.filter(inv => inv.customerId === selectedCustomerId);
        const customerPayments = payments.filter(p => p.customerId === selectedCustomerId);

        const allTx: StatementTransaction[] = [
            ...customerInvoices.map(inv => ({ 
                type: 'invoice' as const, 
                id: inv.id,
                date: new Date(inv.date), 
                description: (t.invoiceDescription ?? 'Invoice #{id}').replace('{id}', inv.invoiceNumber || inv.id.slice(-6)), 
                amount: inv.grandTotal,
                debit: inv.grandTotal,
                credit: 0,
                balance: 0,
                details: inv
            })),
            ...customerPayments.map(p => ({ 
                type: 'payment' as const, 
                id: p.id,
                date: new Date(p.date), 
                description: t.paymentDescription ?? 'Payment',
                amount: p.amount,
                debit: 0,
                credit: p.amount,
                balance: 0,
                details: p
            }))
        ].sort((a, b) => a.date.getTime() - b.date.getTime());

        let openingBalance = selectedCustomer.balance;
        for (let i = allTx.length - 1; i >= 0; i--) {
            const tx = allTx[i];
            if (tx.type === 'invoice') {
                openingBalance -= tx.amount;
            } else {
                openingBalance += tx.amount;
            }
        }
        
        let runningBalance = openingBalance;
        for (const tx of allTx) {
            if (tx.type === 'invoice') {
                runningBalance += tx.amount;
            } else {
                runningBalance -= tx.amount;
            }
            tx.balance = runningBalance;
        }
        
        return { transactions: allTx, openingBalance, finalBalance: runningBalance };
    }, [selectedCustomerId, selectedCustomer, invoices, 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 || !selectedCustomer) return;

        const header = `${t.accountStatementTitle ?? 'Customer Account Statement'} - ${selectedCustomer.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 === 'invoice' && 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`;
                if (row.details.discountAmount && row.details.discountAmount > 0) {
                    detail += `  ${t.discount ?? 'Discount'}: -${formatCurrency(row.details.discountAmount, 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 || !selectedCustomer) return;

        const printWindow = window.open('', '', 'height=600,width=900');
        if (!printWindow) return;

        let htmlContent = `
        <html dir="rtl">
        <head>
            <title>${t.accountStatementTitle ?? 'Customer 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 ?? 'Customer Account Statement'}</h1>
                <p><strong>${t.customerName ?? 'Customer Name'}:</strong> ${selectedCustomer.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, idx) => {
                        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 === 'invoice' && 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.bonus ?? 'Bonus'}</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>${item.bonus || 0}</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>
                                        ${row.details.discountAmount && row.details.discountAmount > 0 ? `<div class="summary-row" style="color: #388e3c;"><span>${t.discount ?? 'Discount'}:</span> <span>-${currencySymbol}${row.details.discountAmount.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 ?? 'Customer Account Statement'}</CardTitle>
                <CardDescription>{t.accountStatementDescription ?? 'Select a customer 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"
                        >
                            {selectedCustomerId
                                ? customers.find((customer) => customer.id === selectedCustomerId)?.name
                                : (t.selectCustomer ?? 'Select a customer...')}
                            <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.searchCustomer ?? 'Search customer...'}
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                autoFocus
                            />
                        </div>
                        <div className="max-h-60 overflow-y-auto">
                            {filteredCustomers.length === 0 ? (
                                <div className="p-2 text-center text-sm text-muted-foreground">
                                    {t.noCustomersFound ?? 'No customers found.'}
                                </div>
                            ) : (
                                filteredCustomers.map((customer) => (
                                    <div
                                        key={customer.id}
                                        onClick={() => {
                                            setSelectedCustomerId(customer.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={customer.id === selectedCustomerId}
                                    >
                                        <Check
                                            className={cn(
                                                "me-2 h-4 w-4",
                                                selectedCustomerId === customer.id ? "opacity-100" : "opacity-0"
                                            )}
                                        />
                                        {customer.name}
                                    </div>
                                ))
                            )}
                        </div>
                    </PopoverContent>
                </Popover>

                {selectedCustomer && (
                    <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 === 'invoice' && (
                                                        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 === 'invoice' && 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-center">{t?.bonus ?? 'Bonus'}</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-center">{item.bonus || 0}</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>
                                                                {row.details.discountAmount && row.details.discountAmount > 0 && (
                                                                    <div className="flex justify-between text-sm text-green-600">
                                                                        <span>{t?.discount ?? 'Discount'}:</span>
                                                                        <span>-{formatCurrency(row.details.discountAmount, 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>
    );
}
