
import React, { useState, useMemo } from 'react';
import {
    Landmark, User, Plus, Wallet, Banknote, CreditCard, Smartphone, X,
    ArrowRightLeft, Calendar, StickyNote, Search, TrendingUp, TrendingDown,
    History, Filter, Pencil, Building2, CircleDollarSign, Activity
} from 'lucide-react';
import { router } from '@inertiajs/react';
import { IntegratedInput, IntegratedSelect, formatCurrency, getCurrentDate } from './CommonUI.tsx';

export function AccountsManagementPage({
                                           accounts, salesHistory, expenses, capital, vendorPayments, notify
                                       }: any) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isTransferModalOpen, setIsTransferModalOpen] = useState(false);
    const [isHistoryOpen, setIsHistoryOpen] = useState(false);
    const [viewingAccount, setViewingAccount] = useState<any>(null);
    const [editingId, setEditingId] = useState<string | null>(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [typeFilter, setTypeFilter] = useState('All');

    // Forms
    const [formData, setFormData] = useState({ name: '', type: 'Cash Counter', balance: '0', status: 'Active' });
    const [transferForm, setTransferForm] = useState({
        fromAccountId: '',
        toAccountId: '',
        amount: '',
        date: getCurrentDate(),
        notes: ''
    });

    // --- Derived Statistics ---
    const stats = useMemo(() => {
        const totalLiquidity = accounts.reduce((acc: number, a: any) => acc + (Number(a.balance) || 0), 0);
        const bankTotal = accounts.filter((a:any) => a.type === 'Bank').reduce((acc: number, a: any) => acc + (Number(a.balance) || 0), 0);
        const cashTotal = accounts.filter((a:any) => a.type === 'Cash Counter').reduce((acc: number, a: any) => acc + (Number(a.balance) || 0), 0);
        return { totalLiquidity, bankTotal, cashTotal };
    }, [accounts]);

    const filteredAccounts = useMemo(() => {
        return accounts.filter((a: any) => {
            const matchesSearch = a.name.toLowerCase().includes(searchTerm.toLowerCase());
            const matchesType = typeFilter === 'All' || a.type === typeFilter;
            return matchesSearch && matchesType;
        });
    }, [accounts, searchTerm, typeFilter]);

    // --- Ledger Reconstruction Logic ---
    // Aggregates data from Sales, Expenses, Capital, and Vendor Payments to show history
    const accountHistory = useMemo(() => {
        if (!viewingAccount) return [];
        const id = viewingAccount.id;
        const txns: any[] = [];

        // 1. Inflows from Sales
        (salesHistory || []).forEach((sale: any) => {
            (sale.payments || []).forEach((pay: any) => {
                if (String(pay.accountId) === String(id)) {
                    txns.push({
                        date: pay.date,
                        type: 'Inflow',
                        category: 'Sale Receipt',
                        desc: `Inv: ${sale.id} - ${sale.customer}`,
                        amount: pay.amount,
                        ref: sale.refNumber
                    });
                }
            });
        });

        // 2. Outflows to Expenses
        (expenses || []).forEach((exp: any) => {
            if (String(exp.accountId) === String(id)) {
                txns.push({
                    date: exp.date,
                    type: 'Outflow',
                    category: 'Expense',
                    desc: exp.description,
                    amount: exp.amount,
                    ref: exp.refNumber
                });
            }
        });

        // 3. Outflows to Vendors
        (vendorPayments || []).forEach((vp: any) => {
            if (String(vp.account_id) === String(id)) {
                txns.push({
                    date: vp.payment_date,
                    type: 'Outflow',
                    category: 'Vendor Payment',
                    desc: vp.notes || 'Stock Purchase',
                    amount: vp.amount,
                    ref: vp.ref_number
                });
            }
        });

        // 4. Capital Adjustments
        (capital || []).forEach((cap: any) => {
            if (String(cap.accountId) === String(id)) {
                txns.push({
                    date: cap.date,
                    type: cap.type === 'Investment' ? 'Inflow' : 'Outflow',
                    category: cap.type,
                    desc: cap.description,
                    amount: cap.amount,
                    ref: cap.refNumber
                });
            }
        });

        return txns.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
    }, [viewingAccount, salesHistory, expenses, capital, vendorPayments]);

    // --- Handlers ---
    const handleSave = () => {
        const url = editingId ? `/accounts/${editingId}` : '/accounts';
        // In a real app, use PUT for update. Here mimicking typical Inertia flow.
        const payload = editingId ? { ...formData, id: editingId } : formData;

        router.post(url, payload, {
            onSuccess: () => {
                setIsModalOpen(false);
                notify(editingId ? 'Account Updated' : 'Account Created');
                resetForm();
            }
        });
    };

    const resetForm = () => {
        setFormData({ name: '', type: 'Cash Counter', balance: '0', status: 'Active' });
        setEditingId(null);
    };

    const openEdit = (account: any) => {
        setEditingId(account.id);
        setFormData({ ...account, balance: String(account.balance) });
        setIsModalOpen(true);
    };

    const handleTransfer = () => {
        if(!transferForm.fromAccountId || !transferForm.toAccountId || !transferForm.amount) return;
        router.post('/accounts/transfer', transferForm, {
            onSuccess: () => {
                setIsTransferModalOpen(false);
                notify('Funds Transferred Successfully');
                setTransferForm({ fromAccountId: '', toAccountId: '', amount: '', date: getCurrentDate(), notes: '' });
            }
        });
    };

    return (
        <div className="animate-fade-in space-y-8 pb-20">
            {/* Header KPI Stats */}
            <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 justify-between relative overflow-hidden group">
                    <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:scale-110 transition-transform"><Landmark size={80}/></div>
                    <div>
                        <p className="text-[10px] font-black text-cyan-400 uppercase tracking-widest mb-1">Total Liquidity</p>
                        <h3 className="text-3xl font-black font-mono tracking-tight">{formatCurrency(stats.totalLiquidity)}</h3>
                        <p className="text-[9px] font-bold text-slate-400 uppercase mt-2">Across {accounts.length} Accounts</p>
                    </div>
                    <div className="w-12 h-12 bg-cyan-500 rounded-2xl flex items-center justify-center text-slate-900 shadow-lg"><Wallet size={24}/></div>
                </div>
                <div className="bg-white rounded-[2rem] p-6 border border-slate-200 shadow-sm flex items-center gap-4">
                    <div className="w-14 h-14 bg-indigo-50 text-indigo-600 rounded-2xl flex items-center justify-center shadow-inner"><Building2 size={28}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Bank Holdings</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{formatCurrency(stats.bankTotal)}</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-14 h-14 bg-emerald-50 text-emerald-600 rounded-2xl flex items-center justify-center shadow-inner"><Banknote size={28}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Cash in Hand</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{formatCurrency(stats.cashTotal)}</p>
                    </div>
                </div>
            </div>

            {/* Controls */}
            <div className="flex flex-col sm:flex-row justify-between items-center gap-4 px-4 lg:px-0">
                <div className="flex gap-2 p-1 bg-white border border-slate-200 rounded-xl shadow-sm overflow-x-auto max-w-full">
                    {['All', 'Cash Counter', 'Bank', 'Mobile Wallet'].map(type => (
                        <button
                            key={type}
                            onClick={() => setTypeFilter(type)}
                            className={`px-4 py-2 rounded-lg text-[10px] font-black uppercase tracking-widest transition-all whitespace-nowrap ${typeFilter === type ? 'bg-slate-900 text-white shadow-md' : 'text-slate-500 hover:bg-slate-50'}`}
                        >
                            {type}
                        </button>
                    ))}
                </div>
                <div className="flex gap-2 w-full sm:w-auto">
                    <div className="relative flex-1 sm:w-64">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
                        <input type="text" placeholder="Search accounts..." className="w-full pl-9 pr-4 py-2.5 bg-white border border-slate-200 rounded-xl text-xs font-bold uppercase tracking-widest outline-none shadow-sm focus:border-indigo-500 transition-all" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
                    </div>
                    <button onClick={() => setIsTransferModalOpen(true)} className="px-4 py-2.5 bg-white border border-slate-200 text-indigo-600 rounded-xl text-[10px] font-black uppercase tracking-widest hover:bg-indigo-50 transition-all flex items-center gap-2 shadow-sm whitespace-nowrap">
                        <ArrowRightLeft size={14} /> Transfer
                    </button>
                    <button onClick={() => { resetForm(); setIsModalOpen(true); }} className="px-4 py-2.5 bg-slate-900 text-white rounded-xl text-[10px] font-black uppercase tracking-widest flex items-center gap-2 hover:bg-black transition-all shadow-lg whitespace-nowrap">
                        <Plus size={14} /> Add New
                    </button>
                </div>
            </div>

            {/* Account Cards Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 px-4 lg:px-0">
                {filteredAccounts.map((a: any) => {
                    // Card Styling Logic
                    const isBank = a.type === 'Bank';
                    const isWallet = a.type === 'Mobile Wallet';
                    const bgClass = isBank ? 'bg-gradient-to-br from-indigo-600 to-blue-700' : isWallet ? 'bg-gradient-to-br from-emerald-500 to-teal-600' : 'bg-gradient-to-br from-slate-800 to-slate-900';
                    const icon = isBank ? <Building2 size={20}/> : isWallet ? <Smartphone size={20}/> : <Wallet size={20}/>;

                    return (
                        <div key={a.id} className={`${bgClass} p-6 rounded-[2rem] shadow-xl text-white relative overflow-hidden group transition-transform hover:-translate-y-1`}>
                            {/* Decorative Background */}
                            <div className="absolute top-0 right-0 p-8 opacity-10 group-hover:scale-110 transition-transform pointer-events-none">
                                <CircleDollarSign size={100}/>
                            </div>

                            <div className="relative z-10 flex flex-col h-48 justify-between">
                                <div className="flex justify-between items-start">
                                    <div className="p-3 bg-white/10 backdrop-blur-md rounded-2xl shadow-inner">
                                        {icon}
                                    </div>
                                    <div className="flex gap-2">
                                        <button onClick={() => { setViewingAccount(a); setIsHistoryOpen(true); }} className="p-2 bg-white/10 hover:bg-white/20 rounded-xl transition-colors backdrop-blur-md" title="View History">
                                            <History size={16} />
                                        </button>
                                        <button onClick={() => openEdit(a)} className="p-2 bg-white/10 hover:bg-white/20 rounded-xl transition-colors backdrop-blur-md" title="Edit Details">
                                            <Pencil size={16} />
                                        </button>
                                    </div>
                                </div>

                                <div>
                                    <p className="text-[10px] font-bold text-white/60 uppercase tracking-widest mb-1">{a.type}</p>
                                    <h4 className="text-xl font-black uppercase tracking-wide truncate">{a.name}</h4>
                                </div>

                                <div className="pt-4 border-t border-white/10 flex justify-between items-end">
                                    <div>
                                        <p className="text-[8px] font-bold text-white/50 uppercase tracking-widest mb-0.5">Current Balance</p>
                                        <p className="text-2xl font-black font-mono tracking-tight">{formatCurrency(a.balance)}</p>
                                    </div>
                                    <span className={`px-2 py-1 rounded text-[8px] font-black uppercase ${a.status === 'Active' ? 'bg-emerald-500/20 text-emerald-100 border border-emerald-500/30' : 'bg-rose-500/20 text-rose-100'}`}>
                                        {a.status}
                                    </span>
                                </div>
                            </div>
                        </div>
                    );
                })}
            </div>

            {/* Create/Edit Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 bg-slate-900/60 z-[100] flex items-center justify-center p-4 backdrop-blur-sm animate-fade-in">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-md p-10 space-y-6 shadow-2xl border border-white/20 relative">
                        <div className="flex justify-between items-center border-b border-slate-100 pb-4">
                            <h3 className="font-black uppercase italic text-sm tracking-widest">{editingId ? 'Edit Account' : 'New Financial Account'}</h3>
                            <button onClick={() => setIsModalOpen(false)} className="p-2 hover:bg-slate-50 rounded-full text-slate-400 transition-colors"><X size={20}/></button>
                        </div>
                        <div className="space-y-4">
                            <IntegratedInput label="Account Title" value={formData.name} onChange={(e:any) => setFormData({...formData, name: e.target.value})} icon={User} placeholder="e.g. Main Cash, HBL" />
                            <IntegratedSelect label="Account Category" value={formData.type} onChange={(e:any) => setFormData({...formData, type: e.target.value})} options={['Cash Counter', 'Bank', 'Mobile Wallet']} icon={Wallet} />
                            <div className="grid grid-cols-2 gap-4">
                                <IntegratedInput label={editingId ? "Current Balance" : "Opening Balance"} value={formData.balance} onChange={(e:any) => setFormData({...formData, balance: e.target.value})} icon={Banknote} />
                                <IntegratedSelect label="Status" value={formData.status} onChange={(e:any) => setFormData({...formData, status: e.target.value})} options={['Active', 'Archived']} icon={Activity} />
                            </div>
                        </div>
                        <button onClick={handleSave} className="w-full bg-slate-900 text-white py-4 rounded-2xl font-black uppercase text-xs tracking-widest hover:bg-black transition-all shadow-lg">
                            {editingId ? 'Update Account' : 'Create Account'}
                        </button>
                    </div>
                </div>
            )}

            {/* Transfer Modal */}
            {isTransferModalOpen && (
                <div className="fixed inset-0 bg-slate-900/60 z-[100] flex items-center justify-center p-4 backdrop-blur-sm animate-fade-in">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-md p-10 space-y-6 shadow-2xl border border-white/20 relative">
                        <div className="flex justify-between items-center border-b border-slate-100 pb-4">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-indigo-50 text-indigo-600 rounded-lg"><ArrowRightLeft size={18} /></div>
                                <h3 className="font-black uppercase italic text-sm tracking-widest">Internal Transfer</h3>
                            </div>
                            <button onClick={() => setIsTransferModalOpen(false)} className="p-2 hover:bg-slate-50 rounded-full text-slate-400 transition-colors"><X size={20}/></button>
                        </div>

                        <div className="space-y-4">
                            <div className="relative">
                                <IntegratedSelect label="From Source" value={transferForm.fromAccountId} onChange={(e:any) => setTransferForm({...transferForm, fromAccountId: e.target.value})} options={accounts} displayKey="name" icon={Wallet} />
                                <div className="absolute left-1/2 -bottom-5 -translate-x-1/2 z-10 bg-white border border-slate-200 p-1.5 rounded-full shadow-sm text-slate-400">
                                    <ArrowRightLeft size={14} className="rotate-90" />
                                </div>
                            </div>
                            <div className="pt-2">
                                <IntegratedSelect label="To Destination" value={transferForm.toAccountId} onChange={(e:any) => setTransferForm({...transferForm, toAccountId: e.target.value})} options={accounts.filter((a:any) => a.id !== transferForm.fromAccountId)} displayKey="name" icon={Landmark} />
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <IntegratedInput label="Amount" value={transferForm.amount} onChange={(e:any) => setTransferForm({...transferForm, amount: e.target.value})} icon={Banknote} />
                            <IntegratedInput label="Date" type="date" value={transferForm.date} onChange={(e:any) => setTransferForm({...transferForm, date: e.target.value})} icon={Calendar} />
                        </div>
                        <IntegratedInput label="Reference / Note" value={transferForm.notes} onChange={(e:any) => setTransferForm({...transferForm, notes: e.target.value})} icon={StickyNote} />

                        <button onClick={handleTransfer} className="w-full bg-slate-900 text-white py-4 rounded-2xl font-black uppercase text-xs tracking-widest hover:bg-black transition-all shadow-lg">Confirm Transfer</button>
                    </div>
                </div>
            )}

            {/* HISTORY MODAL (Derived Ledger) */}
            {isHistoryOpen && viewingAccount && (
                <div className="fixed inset-0 bg-slate-950/80 z-[120] flex items-center justify-center p-4 backdrop-blur-md overflow-y-auto leading-none">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-3xl shadow-2xl my-auto animate-fade-in relative flex flex-col max-h-[85vh] overflow-hidden">
                        <div className="bg-slate-950 p-8 shrink-0 flex justify-between items-center text-white">
                            <div className="flex items-center gap-4">
                                <div className="w-12 h-12 bg-white/10 rounded-2xl flex items-center justify-center text-cyan-400"><History size={24} /></div>
                                <div>
                                    <h3 className="font-black uppercase italic text-sm tracking-widest leading-none">{viewingAccount.name}</h3>
                                    <p className="text-[10px] font-bold text-slate-400 uppercase mt-1 tracking-widest">Transaction Audit Trail</p>
                                </div>
                            </div>
                            <button onClick={() => { setIsHistoryOpen(false); setViewingAccount(null); }} className="p-2 hover:bg-white/10 rounded-full text-slate-400 hover:text-white transition-colors"><X size={20} /></button>
                        </div>

                        <div className="flex-1 overflow-y-auto custom-scrollbar p-6 bg-white">
                            {accountHistory.length === 0 ? (
                                <div className="h-full flex flex-col items-center justify-center text-slate-300 space-y-4">
                                    <History size={48} />
                                    <p className="text-xs font-bold uppercase tracking-widest">No activity recorded</p>
                                </div>
                            ) : (
                                <table className="w-full text-left">
                                    <thead className="bg-slate-50 text-[9px] font-black uppercase text-slate-500 sticky top-0">
                                    <tr>
                                        <th className="px-6 py-4">Date & Ref</th>
                                        <th className="px-6 py-4">Category</th>
                                        <th className="px-6 py-4">Description</th>
                                        <th className="px-6 py-4 text-right">Amount</th>
                                    </tr>
                                    </thead>
                                    <tbody className="divide-y divide-slate-100">
                                    {accountHistory.map((txn: any, idx: number) => (
                                        <tr key={idx} className="hover:bg-slate-50 transition-colors">
                                            <td className="px-6 py-4">
                                                <p className="text-xs font-bold text-slate-700">{txn.date}</p>
                                                <p className="text-[9px] font-bold text-slate-400 font-mono mt-0.5 uppercase">{txn.ref || '---'}</p>
                                            </td>
                                            <td className="px-6 py-4">
                                                    <span className={`px-2 py-1 rounded text-[8px] font-black uppercase tracking-wider ${
                                                        txn.type === 'Inflow' ? 'bg-emerald-50 text-emerald-600' : 'bg-rose-50 text-rose-600'
                                                    }`}>
                                                        {txn.category}
                                                    </span>
                                            </td>
                                            <td className="px-6 py-4 text-[10px] font-bold text-slate-600 uppercase tracking-tight">{txn.desc}</td>
                                            <td className={`px-6 py-4 text-right font-black font-mono text-sm ${
                                                txn.type === 'Inflow' ? 'text-emerald-600' : 'text-rose-600'
                                            }`}>
                                                {txn.type === 'Inflow' ? '+' : '-'}{formatCurrency(txn.amount)}
                                            </td>
                                        </tr>
                                    ))}
                                    </tbody>
                                </table>
                            )}
                        </div>

                        <div className="p-6 bg-slate-50 border-t border-slate-200 shrink-0 text-right">
                            <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-1">Current Net Balance</p>
                            <p className="text-2xl font-black font-mono text-slate-900">{formatCurrency(viewingAccount.balance)}</p>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
