
import React, { useState, useMemo } from 'react';
import {
    ReceiptText, Send, HandCoins, TrendingUp, Truck, X, Layers, DollarSign,
    Calendar, Hash, StickyNote, ArrowDownLeft, CheckCircle2, AlertCircle, Landmark,
    Printer, ArrowRight, Package, FileText, PieChart
} from 'lucide-react';
import { router } from '@inertiajs/react';
import { formatCurrency, getCurrentDate, IntegratedInput, IntegratedSelect } from './CommonUI.tsx';

export function FeesPage({ feeBatches, suppliers, accounts, notify, showroomSettings }: any) {
    const [isSendModalOpen, setIsSendModalOpen] = useState(false);
    const [isSettleModalOpen, setIsSettleModalOpen] = useState(false);
    const [settleBatch, setSettleBatch] = useState<any>(null);
    const [printingBatch, setPrintingBatch] = useState<any>(null); // For Gate Pass

    // --- Forms ---
    const [sendForm, setSendForm] = useState({
        date: getCurrentDate(),
        supplierId: '',
        qty: '',
        rate: '',
        courierRef: '',
        notes: ''
    });

    const [settleForm, setSettleForm] = useState({
        date: getCurrentDate(),
        amount: '',
        accountId: accounts?.[0]?.id || '',
        notes: ''
    });

    // --- Statistics ---
    const stats = useMemo(() => {
        const pendingBatches = (feeBatches || []).filter((b:any) => b.status !== 'Cleared');
        const totalOutstanding = pendingBatches.reduce((acc:number, b:any) => acc + ((b.expectedAmount || b.expected_amount) - (b.receivedAmount || b.received_amount || 0)), 0);
        const totalRecovered = (feeBatches || []).reduce((acc:number, b:any) => acc + (b.receivedAmount || b.received_amount || 0), 0);
        const pendingCount = pendingBatches.length;

        return { totalOutstanding, totalRecovered, pendingCount };
    }, [feeBatches]);

    // --- Helpers ---
    const expectedTotal = useMemo(() => {
        return (Number(sendForm.qty) || 0) * (Number(sendForm.rate) || 0);
    }, [sendForm.qty, sendForm.rate]);

    // Partial Payment Calculation Helper
    const settlementPreview = useMemo(() => {
        if (!settleBatch) return { total: 0, received: 0, remaining: 0, newBalance: 0, newStatus: '' };

        const total = Number(settleBatch.expectedAmount || settleBatch.expected_amount || 0);
        const received = Number(settleBatch.receivedAmount || settleBatch.received_amount || 0);
        const remaining = total - received;
        const payingNow = Number(settleForm.amount) || 0;
        const newBalance = Math.max(0, remaining - payingNow);
        const newStatus = newBalance <= 0 ? 'Cleared' : 'Partial';

        return { total, received, remaining, newBalance, newStatus };
    }, [settleBatch, settleForm.amount]);

    const handleSendSlips = () => {
        if(!sendForm.supplierId || !sendForm.qty) return;
        router.post('/fees', sendForm, {
            onSuccess: () => {
                setIsSendModalOpen(false);
                notify('Service Batch Dispatched');
                setSendForm({ date: getCurrentDate(), supplierId: '', qty: '', rate: '', courierRef: '', notes: '' });
            }
        });
    };

    const openSettleModal = (batch: any) => {
        const remaining = (batch.expectedAmount || batch.expected_amount) - (batch.receivedAmount || batch.received_amount || 0);
        setSettleBatch(batch);
        setSettleForm({
            date: getCurrentDate(),
            amount: remaining > 0 ? remaining.toString() : '',
            accountId: accounts?.[0]?.id || '',
            notes: ''
        });
        setIsSettleModalOpen(true);
    };

    const handleSettle = () => {
        if(!settleBatch || !settleForm.amount) return;
        router.post(`/fees/${settleBatch.id}/settle`, settleForm, {
            onSuccess: () => {
                setIsSettleModalOpen(false);
                setSettleBatch(null);
                notify('Payment Recorded & Ledger Updated');
            }
        });
    };

    const getSupplierName = (id: string) => suppliers.find((s:any) => s.id === id)?.name || 'Unknown Supplier';

    return (
        <div className="animate-fade-in space-y-8 pb-10">
            {/* KPI Header */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 px-4 lg:px-0">
                <div className="bg-slate-900 rounded-[2rem] p-6 text-white shadow-xl flex items-center gap-4">
                    <div className="w-12 h-12 bg-indigo-500 rounded-2xl flex items-center justify-center text-white shadow-lg"><Layers size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-indigo-300 uppercase tracking-widest mb-1">Outstanding Claims</p>
                        <h3 className="text-3xl font-black font-mono tracking-tight">{formatCurrency(stats.totalOutstanding)}</h3>
                    </div>
                </div>
                <div className="bg-white rounded-[2rem] p-6 border border-slate-200 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 bg-emerald-50 text-emerald-600 rounded-xl flex items-center justify-center shadow-inner"><HandCoins size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Total Recovered</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{formatCurrency(stats.totalRecovered)}</p>
                        <p className="text-[8px] font-bold text-emerald-500 uppercase">Realized Profit</p>
                    </div>
                </div>
                <div className="bg-white rounded-[2rem] p-6 border border-slate-200 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 bg-amber-50 text-amber-600 rounded-xl flex items-center justify-center shadow-inner"><ReceiptText size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Pending Batches</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{stats.pendingCount}</p>
                    </div>
                </div>
            </div>

            {/* Controls */}
            <div className="flex justify-between items-center px-4 lg:px-0">
                <div>
                    <h3 className="text-lg font-bold font-heading text-slate-900 uppercase italic">Fee Ledger</h3>
                    <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mt-1">Service Coupon Reimbursements</p>
                </div>
                <button onClick={() => setIsSendModalOpen(true)} className="px-6 py-2.5 bg-slate-900 text-white rounded-xl text-xs font-bold uppercase tracking-widest shadow-lg hover:bg-black transition-all flex items-center gap-2"><Send size={14} /> New Dispatch</button>
            </div>

            {/* Batches Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 px-4 lg:px-0">
                {feeBatches.map((b: any) => {
                    const expected = Number(b.expectedAmount || b.expected_amount || 0);
                    const received = Number(b.receivedAmount || b.received_amount || 0);
                    const remaining = expected - received;
                    const percent = expected > 0 ? (received / expected) * 100 : 0;
                    const isCleared = b.status === 'Cleared';

                    return (
                        <div key={b.id} className="bg-white p-6 rounded-[2rem] border border-slate-200 shadow-sm hover:shadow-md transition-all group flex flex-col relative overflow-hidden">
                            {isCleared && <div className="absolute top-0 right-0 w-20 h-20 bg-emerald-50 rounded-bl-[3rem] -mr-6 -mt-6 z-0"></div>}

                            <div className="flex justify-between items-start mb-4 relative z-10">
                                <div className={`px-3 py-1 rounded-full text-[8px] font-black uppercase border tracking-widest ${isCleared ? 'bg-emerald-100 text-emerald-700 border-emerald-200' : 'bg-amber-50 text-amber-600 border-amber-100'}`}>
                                    {b.status || 'Pending'}
                                </div>
                                <div className="flex gap-2">
                                    <button onClick={() => setPrintingBatch(b)} className="p-1.5 bg-slate-50 text-slate-400 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors" title="Print Gate Pass">
                                        <Printer size={12}/>
                                    </button>
                                </div>
                            </div>

                            <h4 className="font-black text-slate-900 uppercase text-sm truncate mb-1 relative z-10">
                                {getSupplierName(b.supplierId || b.supplier_id)}
                            </h4>
                            <div className="flex items-center gap-3 text-[10px] font-bold text-slate-400 uppercase relative z-10">
                                <span className="flex items-center gap-1"><Calendar size={10}/> {b.date || b.dispatch_date}</span>
                                <span className="flex items-center gap-1"><Package size={10}/> {b.qty} Slips</span>
                            </div>

                            <div className="my-6 space-y-2 relative z-10">
                                <div className="flex justify-between text-[10px] font-bold uppercase">
                                    <span className="text-slate-500">Recovery Progress</span>
                                    <span className={percent >= 100 ? 'text-emerald-600' : 'text-indigo-600'}>{percent.toFixed(0)}%</span>
                                </div>
                                <div className="w-full h-2 bg-slate-100 rounded-full overflow-hidden">
                                    <div className={`h-full transition-all duration-500 ${percent >= 100 ? 'bg-emerald-500' : 'bg-indigo-500'}`} style={{width: `${percent}%`}}></div>
                                </div>
                            </div>

                            <div className="mt-auto flex justify-between items-end border-t border-slate-50 pt-4 relative z-10">
                                <div>
                                    <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-0.5">Claim Value</p>
                                    <p className="text-lg font-black text-slate-900 font-mono tracking-tight">{formatCurrency(expected)}</p>
                                </div>

                                {!isCleared && (
                                    <button onClick={() => openSettleModal(b)} className="px-4 py-2 bg-slate-900 text-white rounded-xl text-[9px] font-black uppercase tracking-widest hover:bg-emerald-600 transition-all flex items-center gap-2 shadow-md">
                                        <ArrowDownLeft size={12}/> Receive
                                    </button>
                                )}
                                {isCleared && (
                                    <div className="flex items-center gap-1 text-emerald-600 text-[9px] font-black uppercase">
                                        <CheckCircle2 size={14}/> Settled
                                    </div>
                                )}
                            </div>
                        </div>
                    );
                })}
                {feeBatches.length === 0 && (
                    <div className="col-span-3 py-20 text-center text-slate-400 text-xs font-bold uppercase italic border-2 border-dashed border-slate-200 rounded-[2rem] bg-slate-50/50">
                        No active claim batches found. Dispatch slips to begin tracking.
                    </div>
                )}
            </div>

            {/* --- DISPATCH MODAL --- */}
            {isSendModalOpen && (
                <div className="fixed inset-0 bg-slate-900/80 z-[100] flex items-center justify-center p-4 backdrop-blur-sm overflow-y-auto">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-lg p-10 space-y-8 shadow-2xl border border-white/20 my-auto animate-fade-in relative">
                        <div className="flex justify-between items-center border-b border-slate-100 pb-6">
                            <div className="flex items-center gap-4">
                                <div className="w-12 h-12 bg-slate-900 rounded-2xl flex items-center justify-center text-white"><Send size={24} /></div>
                                <div>
                                    <h3 className="font-black uppercase italic text-sm tracking-widest leading-none">Dispatch Claims</h3>
                                    <p className="text-[10px] font-bold text-slate-400 uppercase mt-1">Service Coupon Batch</p>
                                </div>
                            </div>
                            <button onClick={() => setIsSendModalOpen(false)} className="p-2 hover:bg-slate-50 rounded-full text-slate-400"><X size={20} /></button>
                        </div>

                        <div className="space-y-5">
                            <IntegratedSelect label="Manufacturer / Supplier" value={sendForm.supplierId} onChange={(e: any) => setSendForm({...sendForm, supplierId: e.target.value})} options={suppliers} displayKey="name" icon={Truck} />

                            <div className="p-5 bg-slate-50 rounded-2xl border border-slate-100 space-y-4">
                                <div className="grid grid-cols-2 gap-4">
                                    <IntegratedInput label="Total Quantity" type="number" value={sendForm.qty} onChange={(e: any) => setSendForm({...sendForm, qty: e.target.value})} icon={Layers} />
                                    <IntegratedInput label="Rate per Slip" type="number" value={sendForm.rate} onChange={(e: any) => setSendForm({...sendForm, rate: e.target.value})} icon={DollarSign} />
                                </div>
                                <div className="flex justify-between items-center pt-2 border-t border-slate-200">
                                    <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Expected Claim Value</span>
                                    <span className="text-lg font-black font-mono text-emerald-600">{formatCurrency(expectedTotal)}</span>
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <IntegratedInput label="Courier Ref / TCS" value={sendForm.courierRef} onChange={(e: any) => setSendForm({...sendForm, courierRef: e.target.value})} icon={StickyNote} placeholder="Tracking #" />
                                <IntegratedInput label="Dispatch Date" type="date" value={sendForm.date} onChange={(e: any) => setSendForm({...sendForm, date: e.target.value})} icon={Calendar} />
                            </div>
                        </div>

                        <button onClick={handleSendSlips} disabled={expectedTotal <= 0} className="w-full bg-slate-900 text-white py-5 rounded-2xl font-black uppercase text-xs tracking-widest shadow-xl hover:bg-black transition-all disabled:opacity-50 disabled:grayscale">
                            Confirm Dispatch
                        </button>
                    </div>
                </div>
            )}

            {/* --- SETTLE MODAL (ENHANCED FOR PARTIAL PAYMENTS) --- */}
            {isSettleModalOpen && settleBatch && (
                <div className="fixed inset-0 bg-slate-900/80 z-[100] flex items-center justify-center p-4 backdrop-blur-sm overflow-y-auto">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-lg p-10 space-y-8 shadow-2xl border border-white/20 my-auto animate-fade-in relative">
                        <div className="flex justify-between items-center border-b border-slate-100 pb-6">
                            <div className="flex items-center gap-4">
                                <div className="w-12 h-12 bg-emerald-500 rounded-2xl flex items-center justify-center text-white"><ArrowDownLeft size={24} /></div>
                                <div>
                                    <h3 className="font-black uppercase italic text-sm tracking-widest leading-none">Receive Payment</h3>
                                    <p className="text-[10px] font-bold text-slate-400 uppercase mt-1">Batch Settlement</p>
                                </div>
                            </div>
                            <button onClick={() => setIsSettleModalOpen(false)} className="p-2 hover:bg-slate-50 rounded-full text-slate-400"><X size={20} /></button>
                        </div>

                        {/* Batch Snapshot */}
                        <div className="p-5 bg-slate-50 rounded-3xl border border-slate-100 space-y-3">
                            <div className="flex justify-between items-center text-[10px] font-bold uppercase text-slate-500">
                                <span>Total Batch Value</span>
                                <span>{formatCurrency(settlementPreview.total)}</span>
                            </div>
                            <div className="flex justify-between items-center text-[10px] font-bold uppercase text-emerald-600">
                                <span>Already Received</span>
                                <span>{formatCurrency(settlementPreview.received)}</span>
                            </div>
                            <div className="w-full h-px bg-slate-200 my-2"></div>
                            <div className="flex justify-between items-center">
                                <span className="text-[9px] font-black text-slate-900 uppercase tracking-widest">Outstanding Balance</span>
                                <span className="text-xl font-black font-mono text-slate-900">{formatCurrency(settlementPreview.remaining)}</span>
                            </div>
                        </div>

                        <div className="space-y-5">
                            <div>
                                <IntegratedInput
                                    label="Amount Received Now (Partial or Full)"
                                    value={settleForm.amount}
                                    onChange={(e: any) => setSettleForm({...settleForm, amount: e.target.value})}
                                    icon={DollarSign}
                                    placeholder="Enter amount..."
                                />
                                {/* Dynamic Status Preview */}
                                <div className="mt-2 flex justify-between items-center px-2">
                                    <span className="text-[9px] font-bold text-slate-400 uppercase">New Balance: <span className="font-mono text-slate-600">{formatCurrency(settlementPreview.newBalance)}</span></span>
                                    <span className={`text-[9px] font-black uppercase px-2 py-0.5 rounded border ${settlementPreview.newStatus === 'Cleared' ? 'bg-emerald-50 text-emerald-600 border-emerald-100' : 'bg-amber-50 text-amber-600 border-amber-100'}`}>
                                        Status: {settlementPreview.newStatus}
                                    </span>
                                </div>
                            </div>

                            <IntegratedSelect label="Deposit To Account" value={settleForm.accountId} onChange={(e: any) => setSettleForm({...settleForm, accountId: e.target.value})} options={accounts} displayKey="name" icon={Landmark} />

                            <div className="grid grid-cols-2 gap-4">
                                <IntegratedInput label="Date" type="date" value={settleForm.date} onChange={(e: any) => setSettleForm({...settleForm, date: e.target.value})} icon={Calendar} />
                                <IntegratedInput label="Notes" value={settleForm.notes} onChange={(e: any) => setSettleForm({...settleForm, notes: e.target.value})} icon={StickyNote} placeholder="Cheque No / Ref" />
                            </div>
                        </div>

                        <div className="pt-2">
                            <div className="flex items-center gap-2 mb-3 bg-emerald-50/50 p-2 rounded-lg justify-center">
                                <PieChart size={12} className="text-emerald-600"/>
                                <p className="text-[8px] font-bold text-emerald-700 uppercase">Note: This amount will be recorded as NET PROFIT</p>
                            </div>
                            <button onClick={handleSettle} className="w-full bg-emerald-600 text-white py-5 rounded-2xl font-black uppercase text-xs tracking-widest shadow-xl hover:bg-emerald-700 transition-all">
                                Confirm Receipt
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* --- PRINT GATE PASS MODAL --- */}
            {printingBatch && (
                <div className="fixed inset-0 bg-slate-950/90 z-[200] flex items-center justify-center p-4 backdrop-blur-xl overflow-y-auto">
                    <div className="bg-white w-full max-w-2xl rounded-[1rem] shadow-2xl overflow-hidden relative">
                        <div className="bg-slate-900 p-4 flex justify-between items-center text-white no-print">
                            <h3 className="font-black uppercase text-xs tracking-widest">Gate Pass Preview</h3>
                            <div className="flex gap-2">
                                <button onClick={() => window.print()} className="px-4 py-2 bg-cyan-600 rounded-lg text-[10px] font-bold uppercase tracking-widest flex items-center gap-2"><Printer size={12}/> Print Pass</button>
                                <button onClick={() => setPrintingBatch(null)} className="p-2 hover:bg-white/10 rounded-lg"><X size={16}/></button>
                            </div>
                        </div>

                        <div className="p-16 bg-white text-slate-900 print-content">
                            <div className="border-b-2 border-slate-900 pb-8 mb-8 flex justify-between items-start">
                                <div>
                                    <h1 className="text-3xl font-black uppercase italic tracking-tighter">{showroomSettings?.showroomName || 'SHOWROOM'}</h1>
                                    <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest mt-2">Service Claim Dispatch Note</p>
                                </div>
                                <div className="text-right">
                                    <p className="text-xl font-mono font-black">BATCH-{printingBatch.id.substring(0,6).toUpperCase()}</p>
                                    <p className="text-[10px] font-bold text-slate-400 uppercase">{printingBatch.date || printingBatch.dispatch_date}</p>
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-12 mb-12">
                                <div>
                                    <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-2">Dispatched To</p>
                                    <h4 className="text-xl font-black uppercase">{getSupplierName(printingBatch.supplierId || printingBatch.supplier_id)}</h4>
                                    <p className="text-xs font-medium text-slate-500 mt-1 uppercase">Claims Department</p>
                                </div>
                                <div className="text-right">
                                    <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-2">Dispatch Details</p>
                                    <p className="text-sm font-bold uppercase">Courier: {printingBatch.courierRef || 'Hand Carry'}</p>
                                    <p className="text-xs text-slate-500 mt-1">Ref: {printingBatch.id}</p>
                                </div>
                            </div>

                            <table className="w-full text-left mb-12 border-collapse">
                                <thead>
                                <tr className="border-b-2 border-slate-900">
                                    <th className="py-3 text-[10px] font-black uppercase tracking-widest">Description</th>
                                    <th className="py-3 text-[10px] font-black uppercase tracking-widest text-center">Qty</th>
                                    <th className="py-3 text-[10px] font-black uppercase tracking-widest text-right">Rate</th>
                                    <th className="py-3 text-[10px] font-black uppercase tracking-widest text-right">Amount</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                    <td className="py-4 text-xs font-bold uppercase">Service Coupons / Warranty Claims</td>
                                    <td className="py-4 text-xs font-bold text-center">{printingBatch.qty}</td>
                                    <td className="py-4 text-xs font-bold text-right font-mono">{formatCurrency(printingBatch.rate)}</td>
                                    <td className="py-4 text-xs font-black text-right font-mono">{formatCurrency(printingBatch.expectedAmount || printingBatch.expected_amount)}</td>
                                </tr>
                                </tbody>
                                <tfoot>
                                <tr className="border-t border-slate-200">
                                    <td colSpan={3} className="py-4 text-right text-xs font-black uppercase tracking-widest">Total Declared Value</td>
                                    <td className="py-4 text-right text-lg font-black font-mono">{formatCurrency(printingBatch.expectedAmount || printingBatch.expected_amount)}</td>
                                </tr>
                                </tfoot>
                            </table>

                            <div className="grid grid-cols-2 gap-12 mt-20">
                                <div className="border-t border-slate-300 pt-2">
                                    <p className="text-[8px] font-bold text-slate-400 uppercase tracking-widest text-center">Authorized Signature</p>
                                </div>
                                <div className="border-t border-slate-300 pt-2">
                                    <p className="text-[8px] font-bold text-slate-400 uppercase tracking-widest text-center">Courier / Receiver</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <style>{`@media print { .no-print { display: none; } body { background: white; } .print-content { padding: 0 !important; } }`}</style>
                </div>
            )}
        </div>
    );
}
