import { Head, useForm } from '@inertiajs/react';
import { useState } from 'react';
import AppLayout from '@/Layouts/AppLayout';
import { Plus, X, ArrowRightLeft, Wallet, Landmark, Smartphone, CreditCard, Edit2 } from 'lucide-react';

const fmt = (n) => '₦' + new Intl.NumberFormat('en-NG').format(n ?? 0);

const typeIcons = {
    cash:         { icon: Wallet,      label: 'Cash',         bg: 'bg-green-100',  text: 'text-green-600' },
    bank:         { icon: Landmark,    label: 'Bank',         bg: 'bg-blue-100',   text: 'text-blue-600' },
    mobile_money: { icon: Smartphone,  label: 'Mobile Money', bg: 'bg-purple-100', text: 'text-purple-600' },
    pos:          { icon: CreditCard,  label: 'POS',          bg: 'bg-orange-100', text: 'text-orange-600' },
};

function AccountModal({ account, onClose }) {
    const isEdit = !!account;
    const { data, setData, post, put, processing, errors } = useForm({
        name:            account?.name ?? '',
        type:            account?.type ?? 'bank',
        bank_name:       account?.bank_name ?? '',
        account_number:  account?.account_number ?? '',
        opening_balance: account?.opening_balance ?? '',
    });

    const submit = (e) => {
        e.preventDefault();
        const opts = { onSuccess: onClose };
        isEdit ? put(`/dashboard/accounts/${account.id}`, opts) : post('/dashboard/accounts', opts);
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
            <div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6">
                <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-gray-900">{isEdit ? 'Edit Account' : 'Add Account'}</h3>
                    <button onClick={onClose}><X className="w-5 h-5 text-gray-400" /></button>
                </div>
                <form onSubmit={submit} className="space-y-3">
                    <div>
                        <label className="block text-xs font-medium text-gray-600 mb-1">Account Name *</label>
                        <input value={data.name} onChange={e => setData('name', e.target.value)}
                            className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                        {errors.name && <p className="text-red-500 text-xs mt-1">{errors.name}</p>}
                    </div>
                    <div>
                        <label className="block text-xs font-medium text-gray-600 mb-1">Type *</label>
                        <select value={data.type} onChange={e => setData('type', e.target.value)}
                            className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            {Object.entries(typeIcons).map(([k, v]) => (
                                <option key={k} value={k}>{v.label}</option>
                            ))}
                        </select>
                    </div>
                    {data.type === 'bank' && (
                        <>
                            <div>
                                <label className="block text-xs font-medium text-gray-600 mb-1">Bank Name</label>
                                <input value={data.bank_name} onChange={e => setData('bank_name', e.target.value)}
                                    placeholder="e.g. GTBank, Access Bank"
                                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                            </div>
                            <div>
                                <label className="block text-xs font-medium text-gray-600 mb-1">Account Number</label>
                                <input value={data.account_number} onChange={e => setData('account_number', e.target.value)}
                                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                            </div>
                        </>
                    )}
                    {!isEdit && (
                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">Opening Balance (₦) *</label>
                            <input type="number" min="0" value={data.opening_balance} onChange={e => setData('opening_balance', e.target.value)}
                                className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                            {errors.opening_balance && <p className="text-red-500 text-xs mt-1">{errors.opening_balance}</p>}
                        </div>
                    )}
                    <div className="flex gap-2 pt-1">
                        <button type="button" onClick={onClose} className="flex-1 py-2 border border-gray-200 rounded-lg text-sm text-gray-600">Cancel</button>
                        <button type="submit" disabled={processing} className="flex-1 py-2 bg-blue-600 text-white rounded-lg text-sm disabled:opacity-50">
                            {isEdit ? 'Save' : 'Add Account'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}

function TransferModal({ accounts, onClose }) {
    const { data, setData, post, processing, errors } = useForm({
        from_account_id: '',
        to_account_id: '',
        amount: '',
        description: '',
    });

    const submit = (e) => {
        e.preventDefault();
        post('/dashboard/accounts/transfer', { onSuccess: onClose });
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
            <div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6">
                <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-gray-900">Transfer Between Accounts</h3>
                    <button onClick={onClose}><X className="w-5 h-5 text-gray-400" /></button>
                </div>
                <form onSubmit={submit} className="space-y-3">
                    <div>
                        <label className="block text-xs font-medium text-gray-600 mb-1">From Account *</label>
                        <select value={data.from_account_id} onChange={e => setData('from_account_id', e.target.value)}
                            className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Select account</option>
                            {accounts.map(a => <option key={a.id} value={a.id}>{a.name} — {fmt(a.current_balance)}</option>)}
                        </select>
                        {errors.from_account_id && <p className="text-red-500 text-xs mt-1">{errors.from_account_id}</p>}
                    </div>
                    <div>
                        <label className="block text-xs font-medium text-gray-600 mb-1">To Account *</label>
                        <select value={data.to_account_id} onChange={e => setData('to_account_id', e.target.value)}
                            className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Select account</option>
                            {accounts.filter(a => a.id !== +data.from_account_id).map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
                        </select>
                        {errors.to_account_id && <p className="text-red-500 text-xs mt-1">{errors.to_account_id}</p>}
                    </div>
                    <div>
                        <label className="block text-xs font-medium text-gray-600 mb-1">Amount (₦) *</label>
                        <input type="number" min="1" value={data.amount} onChange={e => setData('amount', e.target.value)}
                            className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                        {errors.amount && <p className="text-red-500 text-xs mt-1">{errors.amount}</p>}
                    </div>
                    <div>
                        <label className="block text-xs font-medium text-gray-600 mb-1">Description</label>
                        <input value={data.description} onChange={e => setData('description', e.target.value)}
                            placeholder="e.g. Weekly cash withdrawal"
                            className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                    </div>
                    <div className="flex gap-2 pt-1">
                        <button type="button" onClick={onClose} className="flex-1 py-2 border border-gray-200 rounded-lg text-sm text-gray-600">Cancel</button>
                        <button type="submit" disabled={processing} className="flex-1 py-2 bg-blue-600 text-white rounded-lg text-sm disabled:opacity-50">Transfer</button>
                    </div>
                </form>
            </div>
        </div>
    );
}

export default function AccountsIndex({ accounts, transfers, total_balance }) {
    const [showAdd, setShowAdd] = useState(false);
    const [editAccount, setEditAccount] = useState(null);
    const [showTransfer, setShowTransfer] = useState(false);

    return (
        <AppLayout title="Accounts">
            <Head title="Accounts" />
            {showAdd && <AccountModal onClose={() => setShowAdd(false)} />}
            {editAccount && <AccountModal account={editAccount} onClose={() => setEditAccount(null)} />}
            {showTransfer && <TransferModal accounts={accounts} onClose={() => setShowTransfer(false)} />}

            <div className="space-y-5">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div className="bg-white rounded-xl border border-gray-200 p-4 flex items-center gap-3">
                        <Wallet className="w-5 h-5 text-blue-600" />
                        <div>
                            <p className="text-xl font-bold text-gray-900">{fmt(total_balance)}</p>
                            <p className="text-xs text-gray-500">Total Balance Across All Accounts</p>
                        </div>
                    </div>
                    <div className="flex gap-2">
                        {accounts.length >= 2 && (
                            <button onClick={() => setShowTransfer(true)}
                                className="flex items-center gap-1.5 px-4 py-2 border border-gray-200 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-50">
                                <ArrowRightLeft className="w-4 h-4" /> Transfer
                            </button>
                        )}
                        <button onClick={() => setShowAdd(true)}
                            className="flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700">
                            <Plus className="w-4 h-4" /> Add Account
                        </button>
                    </div>
                </div>

                {/* Account Cards */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {accounts.map(account => {
                        const t = typeIcons[account.type] ?? typeIcons.cash;
                        const Icon = t.icon;
                        return (
                            <div key={account.id} className="bg-white rounded-xl border border-gray-200 p-5">
                                <div className="flex items-start justify-between mb-4">
                                    <div className={`w-10 h-10 rounded-xl ${t.bg} flex items-center justify-center`}>
                                        <Icon className={`w-5 h-5 ${t.text}`} />
                                    </div>
                                    <button onClick={() => setEditAccount(account)} className="p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded">
                                        <Edit2 className="w-3.5 h-3.5" />
                                    </button>
                                </div>
                                <p className="font-semibold text-gray-900">{account.name}</p>
                                {account.bank_name && <p className="text-xs text-gray-400 mt-0.5">{account.bank_name}{account.account_number ? ` · ${account.account_number}` : ''}</p>}
                                <p className="text-2xl font-bold text-gray-900 mt-3">{fmt(account.current_balance)}</p>
                                <p className="text-xs text-gray-400 mt-1 capitalize">{t.label}</p>
                                {account.is_default && (
                                    <span className="mt-2 inline-block px-2 py-0.5 bg-blue-50 text-blue-600 text-xs rounded-full">Default</span>
                                )}
                            </div>
                        );
                    })}
                    {accounts.length === 0 && (
                        <div className="col-span-3 bg-white rounded-xl border border-dashed border-gray-300 p-12 text-center text-gray-400">
                            <Wallet className="w-10 h-10 mx-auto mb-3 text-gray-300" />
                            <p className="font-medium text-gray-500 mb-1">No accounts yet</p>
                            <p className="text-sm">Add your cash, bank, or mobile money accounts</p>
                        </div>
                    )}
                </div>

                {/* Recent Transfers */}
                {transfers.length > 0 && (
                    <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
                        <div className="px-5 py-4 border-b border-gray-100">
                            <h3 className="font-semibold text-gray-900">Recent Transfers</h3>
                        </div>
                        <table className="w-full text-sm">
                            <thead className="bg-gray-50 border-b border-gray-100">
                                <tr className="text-left text-gray-500">
                                    <th className="px-4 py-2.5 font-medium">From</th>
                                    <th className="px-4 py-2.5 font-medium">To</th>
                                    <th className="px-4 py-2.5 font-medium hidden md:table-cell">Description</th>
                                    <th className="px-4 py-2.5 font-medium">Amount</th>
                                    <th className="px-4 py-2.5 font-medium hidden md:table-cell">Date</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-50">
                                {transfers.map(t => (
                                    <tr key={t.id} className="hover:bg-gray-50">
                                        <td className="px-4 py-3 text-gray-900">{t.from_account?.name ?? '—'}</td>
                                        <td className="px-4 py-3 text-gray-900">{t.to_account?.name ?? '—'}</td>
                                        <td className="px-4 py-3 text-gray-500 hidden md:table-cell">{t.description ?? '—'}</td>
                                        <td className="px-4 py-3 font-semibold text-gray-900">{fmt(t.amount)}</td>
                                        <td className="px-4 py-3 text-gray-400 text-xs hidden md:table-cell">{t.transferred_at?.split('T')[0]}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </AppLayout>
    );
}
