import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Plus, RefreshCw, AlertCircle, Loader2, X, Building2,
  ChevronLeft, ChevronRight, Eye, Pencil, Trash2, Wallet, Scale,
} from 'lucide-react';
import { useFinanceStore, BankAccount } from '../../store/finance';
import { Modal, ModalBody } from '../../components/ui/Modal';

const PAGE_SIZE = 25;

const currency = (n: number) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(Number.isFinite(n) ? n : 0);

const statusBadge = (balance: number) =>
  balance > 0 ? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300'
               : 'bg-muted text-text-muted border-border';

const accountTypeLabel = (t: string) => {
  if (t === 'bank') return 'Bank';
  if (t === 'cash') return 'Cash';
  if (t === 'mobile_money') return 'Mobile money';
  return t;
};

export default function BankingAccounts() {
  const navigate = useNavigate();
  const {
    bankAccounts, reconciliations, loading, error,
    fetchBankAccounts, createBankAccount, updateBankAccount, deleteBankAccount,
    fetchReconciliations,
  } = useFinanceStore();
  const [search, setSearch] = useState('');
  const [type, setType] = useState('');
  const [page, setPage] = useState(0);
  const [editor, setEditor] = useState<{ row?: BankAccount; creating?: boolean } | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<BankAccount | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    fetchBankAccounts();
    fetchReconciliations();
  }, [fetchBankAccounts, fetchReconciliations]);

  const filtered = useMemo(() => {
    return bankAccounts.filter((b) => {
      if (type && b.account_type !== type) return false;
      if (!search.trim()) return true;
      const needle = search.toLowerCase();
      return (b.name || '').toLowerCase().includes(needle) || (b.bank_name || '').toLowerCase().includes(needle);
    });
  }, [bankAccounts, type, search]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const pageRows = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);

  const totals = useMemo(() => {
    let balance = 0;
    filtered.forEach((b) => { balance += Number(b.current_balance) || 0; });
    return { balance, count: filtered.length, unreconciled: reconciliations.filter((r) => r.status === 'discrepancy').length };
  }, [filtered, reconciliations]);

  const save = async (data: Partial<BankAccount> & { chart_account_uid?: string | null }) => {
    setBusy(true);
    if (editor?.row && !editor.creating) {
      const r = await updateBankAccount(editor.row.uid, data);
      setBusy(false);
      if (r) setEditor(null);
    } else {
      const r = await createBankAccount(data);
      setBusy(false);
      if (r) setEditor(null);
    }
  };

  const onDelete = async (b: BankAccount) => {
    setBusy(true);
    const ok = await deleteBankAccount(b.uid);
    setBusy(false);
    if (ok) setConfirmDelete(null);
  };

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Banking</h1>
          <p className="text-text-muted mt-1 text-lg">Bank accounts, mobile money, and reconciliation sessions.</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => { fetchBankAccounts(); fetchReconciliations(); }} className="flex items-center gap-2 px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">
            <RefreshCw size={16} /> Refresh
          </button>
          <button onClick={() => setEditor({ creating: true })} className="flex items-center gap-2 bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl font-semibold transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98]">
            <Plus size={18} /> New Account
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
        <Summary icon={Building2} label="Accounts" value={totals.count} />
        <Summary icon={Wallet} label="Total balance" value={currency(totals.balance)} tone="emerald" />
        <Summary icon={Scale} label="Sessions needing review" value={totals.unreconciled} tone={totals.unreconciled > 0 ? 'rose' : 'emerald'} />
      </div>

      {/* Filters */}
      <div className="bg-card rounded-2xl border border-border p-5 shadow-sm">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div className="relative sm:col-span-2">
            <Plus size={16} className="hidden" />
            <input type="text" placeholder="Search name, bank…" value={search} onChange={(e) => { setSearch(e.target.value); setPage(0); }} className="w-full px-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
          </div>
          <select value={type} onChange={(e) => { setType(e.target.value); setPage(0); }} className="px-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30">
            <option value="">All types</option>
            <option value="bank">Bank</option>
            <option value="cash">Cash</option>
            <option value="mobile_money">Mobile money</option>
          </select>
        </div>
      </div>

      {error && (
        <div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900 rounded-2xl p-4 flex items-center gap-3 text-red-700 dark:text-red-300">
          <AlertCircle size={18} />
          <span className="text-sm">{error}</span>
        </div>
      )}

      {/* Accounts table */}
      <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-muted/80 border-b border-border">
              <tr>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Account</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Type</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Current balance</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Status</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {pageRows.length > 0 ? (
                pageRows.map((b) => (
                  <tr key={b.uid} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <div className="p-1.5 rounded-md bg-primary/10 text-primary"><Building2 size={14} /></div>
                        <div>
                          <p className="text-[0.85rem] font-semibold text-text">{b.name}</p>
                          <p className="text-[0.65rem] text-text-muted">{b.bank_name || '—'} · {b.account_number || ''} · {b.currency}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-secondary">{accountTypeLabel(b.account_type)}</td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-bold text-text whitespace-nowrap">{currency(Number(b.current_balance))}</td>
                    <td className="px-6 py-4">
                      <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${statusBadge(Number(b.current_balance))}`}>{b.is_active ? 'Active' : 'Disabled'}</span>
                    </td>
                    <td className="px-6 py-4 text-right whitespace-nowrap">
                      <div className="inline-flex items-center gap-1">
                        <button onClick={() => navigate(`/finance/banking/reconcile/new?account=${b.uid}`)} className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all" title="Run reconciliation" aria-label="Run reconciliation">
                          <Scale size={16} />
                        </button>
                        <button onClick={() => setEditor({ row: b, creating: false })} className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all" title="Edit" aria-label="Edit">
                          <Pencil size={16} />
                        </button>
                        <button onClick={() => setConfirmDelete(b)} className="p-2 rounded-lg hover:bg-red-500 hover:text-white text-text-muted transition-all" title="Delete" aria-label="Delete">
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr><td colSpan={5} className="px-6 py-10 text-center text-text-muted text-sm">No bank accounts yet — add one to begin.</td></tr>
              )}
            </tbody>
          </table>
        </div>
        <div className="px-6 py-4 border-t border-border bg-muted/30 flex items-center justify-between">
          <span className="text-[0.7rem] font-bold text-text-muted">Page {page + 1} of {totalPages}</span>
          <div className="inline-flex items-center gap-2">
            <button disabled={page === 0} onClick={() => setPage((p) => Math.max(0, p - 1))} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all">
              <ChevronLeft size={14} /> Prev
            </button>
            <button disabled={page + 1 >= totalPages} onClick={() => setPage((p) => p + 1)} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all">
              Next <ChevronRight size={14} />
            </button>
          </div>
        </div>
      </div>

      {/* Recent reconciliations */}
      <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
        <div className="px-6 py-4 border-b border-border bg-muted/30 flex items-center justify-between">
          <h3 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">Recent reconciliation sessions</h3>
          <button
            onClick={() => navigate('/finance/banking/reconcile/new')}
            className="flex items-center gap-1 text-xs font-bold text-primary hover:underline"
          >
            <Plus size={12} /> New session
          </button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-card">
              <tr>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Account</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Period</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Statement</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Book</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Status</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {reconciliations.length > 0 ? (
                reconciliations.slice(0, 10).map((r) => (
                  <tr key={r.uid} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-3 text-[0.85rem] font-semibold text-text">{r.account_name}</td>
                    <td className="px-6 py-3 text-[0.75rem] font-mono text-text-muted">{r.period_start} → {r.period_end}</td>
                    <td className="px-6 py-3 text-right text-[0.85rem] font-mono">{currency(Number(r.statement_balance))}</td>
                    <td className="px-6 py-3 text-right text-[0.85rem] font-mono">{currency(Number(r.book_balance || 0))}</td>
                    <td className="px-6 py-3">
                      <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${
                        r.status === 'balanced' ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-amber-50 text-amber-700 border-amber-200'
                      }`}>{r.status}</span>
                    </td>
                    <td className="px-6 py-3 text-right">
                      <button onClick={() => navigate(`/finance/banking/reconciliations/${r.uid}`)} className="flex items-center gap-1 text-xs font-bold text-primary hover:underline">
                        <Eye size={12} /> Review
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr><td colSpan={6} className="px-6 py-6 text-center text-text-muted text-sm">No reconciliation sessions yet.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {editor && (
        <BankAccountEditor
          initial={editor.row}
          isCreating={!!editor.creating}
          busy={busy}
          onSave={save}
          onClose={() => setEditor(null)}
        />
      )}

      {confirmDelete && (
        <Modal
          open={true}
          onClose={() => setConfirmDelete(null)}
          title="Delete bank account?"
          icon={Trash2}
          maxWidth="max-w-sm"
          footer={
            <>
              <button onClick={() => setConfirmDelete(null)} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
              <button onClick={() => onDelete(confirmDelete)} disabled={busy} className="px-4 py-2 rounded-xl bg-red-500 text-white text-sm font-bold hover:bg-red-600 transition-all">{busy ? <Loader2 size={14} className="animate-spin" /> : 'Delete'}</button>
            </>
          }
        >
          <p className="text-sm text-text-muted">Delete <strong>{confirmDelete.name}</strong>? Soft-delete; past reconciliations stay intact.</p>
        </Modal>
      )}
    </div>
  );
}

function Summary({
  icon: Icon, label, value, tone,
}: {
  icon: typeof Building2;
  label: string;
  value: string | number;
  tone?: 'emerald' | 'rose';
}) {
  const colorCls = tone === 'emerald' ? 'text-emerald-600' : tone === 'rose' ? 'text-rose-600' : 'text-text';
  return (
    <div className="bg-card border border-border rounded-2xl p-4 shadow-sm">
      <div className="flex items-center gap-2 mb-1">
        <Icon size={14} className="text-text-muted" />
        <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">{label}</p>
      </div>
      <p className={`text-2xl font-black ${colorCls}`}>{value}</p>
    </div>
  );
}

function BankAccountEditor({
  initial, isCreating, busy, onSave, onClose,
}: {
  initial?: BankAccount;
  isCreating: boolean;
  busy: boolean;
  onSave: (data: Partial<BankAccount> & { chart_account_uid?: string | null }) => Promise<unknown>;
  onClose: () => void;
}) {
  const [name, setName] = useState(initial?.name || '');
  const [bankName, setBankName] = useState(initial?.bank_name || '');
  const [accountNumber, setAccountNumber] = useState(initial?.account_number || '');
  const [accountType, setAccountType] = useState<BankAccount['account_type']>(initial?.account_type || 'bank');
  const [currency_, setCurrency] = useState(initial?.currency || 'USD');
  const [opening, setOpening] = useState(String(initial?.opening_balance ?? 0));
  const [currentBal, setCurrentBal] = useState(String(initial?.current_balance ?? 0));
  const [active, setActive] = useState(initial ? !!initial.is_active : true);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;
    await onSave({
      name: name.trim(),
      bank_name: bankName.trim() || null,
      account_number: accountNumber.trim() || null,
      account_type: accountType,
      currency: currency_.trim() || 'USD',
      opening_balance: Number(opening) || 0,
      current_balance: Number(currentBal) || 0,
      is_active: active ? 1 : 0,
    });
  };

  return (
    <Modal
      open={true}
      onClose={onClose}
      title={isCreating ? 'New bank account' : `Edit ${initial?.name}`}
      maxWidth="max-w-md"
      footer={
        <>
          <button type="button" onClick={onClose} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
          <button type="submit" form="bank-account-form" disabled={busy || !name.trim()} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-primary text-white text-sm font-bold hover:bg-primary-dark disabled:opacity-40 transition-all">
            {busy && <Loader2 size={14} className="animate-spin" />}
            <span>{isCreating ? 'Create' : 'Save'}</span>
          </button>
        </>
      }
    >
      <form id="bank-account-form" onSubmit={submit}>
        <Field label="Name *" value={name} onChange={setName} required />
        <Field label="Bank name" value={bankName} onChange={setBankName} />
        <Field label="Account number (last4)" value={accountNumber} onChange={setAccountNumber} />
        <div className="grid grid-cols-2 gap-3 mt-3">
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Type</span>
            <select value={accountType} onChange={(e) => setAccountType(e.target.value as any)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30">
              <option value="bank">Bank</option>
              <option value="cash">Cash</option>
              <option value="mobile_money">Mobile money</option>
            </select>
          </label>
          <Field label="Currency" value={currency_} onChange={setCurrency} />
        </div>
        <div className="grid grid-cols-2 gap-3 mt-3">
          <Field label="Opening balance" type="number" value={opening} onChange={setOpening} />
          <Field label="Current balance" type="number" value={currentBal} onChange={setCurrentBal} />
        </div>
        <label className="flex items-center gap-2 mt-3 text-sm">
          <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} className="accent-primary" />
          <span>Active</span>
        </label>
      </form>
    </Modal>
  );
}

function Field({
  label, value, onChange, type = 'text', required,
}: {
  label: string; value: string; onChange: (v: string) => void;
  type?: string; required?: boolean;
}) {
  return (
    <label className="block mt-3">
      <span className="text-xs font-bold uppercase tracking-wider text-text-muted">{label}</span>
      <input type={type} required={required} value={value} onChange={(e) => onChange(e.target.value)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
    </label>
  );
}
