import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import {
  Plus, RefreshCw, AlertCircle, Loader2, X,
  Scale, CheckCircle2, XCircle, Trash2, Building2,
  ArrowLeft, Save, Clock, Eye,
} from 'lucide-react';
import { useFinanceStore } from '../../store/finance';
import { Reconciliation } from '../../store/finance';

interface LineDraft {
  date: string;
  amount: string;
  reference: string;
}

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

const statusBadge = (status: string) => {
  const s = status.toLowerCase();
  if (s === 'balanced') return 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300';
  if (s === 'discrepancy') return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/20 dark:text-rose-300';
  return 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300';
};

const matchBadge = (status: string) => {
  const s = status.toLowerCase();
  if (s === 'matched') return 'bg-emerald-50 text-emerald-700 border-emerald-200';
  if (s === 'ignored') return 'bg-muted text-text-muted border-border';
  return 'bg-rose-50 text-rose-700 border-rose-200';
};

export default function BankingReconcile() {
  const navigate = useNavigate();
  const { uid } = useParams<{ uid: string }>();
  const [searchParams] = useSearchParams();
  const {
    bankAccounts, reconciliations,
    fetchBankAccounts, fetchReconciliations, fetchReconciliation,
    reconcileBank, resolveReconciliationLine,
  } = useFinanceStore();

  const [detail, setDetail] = useState<Reconciliation | null>(null);
  const [loadingDetail, setLoadingDetail] = useState(false);

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

  useEffect(() => {
    let mounted = true;
    if (!uid) return;
    (async () => {
      setLoadingDetail(true);
      const r = await fetchReconciliation(uid);
      if (mounted) {
        setDetail(r);
        setLoadingDetail(false);
      }
    })();
    return () => { mounted = false; };
  }, [uid, fetchReconciliation]);

  if (uid) {
    return (
      <DetailMode
        reconciliation={detail}
        loading={loadingDetail}
        navigate={navigate}
        resolve={async (line_id, action, payment_id) => {
          const r = await resolveReconciliationLine(uid, line_id, action, payment_id);
          if (r) {
            const refreshed = await fetchReconciliation(uid);
            setDetail(refreshed);
          }
          return r;
        }}
      />
    );
  }

  return (
    <NewSessionMode
      bankAccounts={bankAccounts}
      reconciliations={reconciliations}
      initialAccountUid={searchParams.get('account') || undefined}
      reconcile={reconcileBank}
      onCreated={(r) => navigate(`/finance/banking/reconciliations/${r.uid}`)}
      navigate={navigate}
    />
  );
}

function NewSessionMode({
  bankAccounts, reconciliations, initialAccountUid, reconcile, onCreated, navigate,
}: {
  bankAccounts: import('../../store/finance').BankAccount[];
  reconciliations: Reconciliation[];
  initialAccountUid?: string;
  reconcile: (data: any) => Promise<{ uid: string; matched: number; unmatched: number } | null>;
  onCreated: (r: { uid: string }) => void;
  navigate: ReturnType<typeof useNavigate>;
}) {
  const [accountUid, setAccountUid] = useState(initialAccountUid || bankAccounts[0]?.uid || '');
  const [periodStart, setPeriodStart] = useState(new Date().toISOString().slice(0, 7) + '-01');
  const [periodEnd, setPeriodEnd] = useState(new Date().toISOString().slice(0, 10));
  const [statementBalance, setStatementBalance] = useState('0');
  const [lines, setLines] = useState<LineDraft[]>([
    { date: new Date().toISOString().slice(0, 10), amount: '', reference: '' },
  ]);
  const [busy, setBusy] = useState(false);
  const [banner, setBanner] = useState<{ kind: 'ok' | 'err'; msg: string } | null>(null);

  useEffect(() => {
    if (!accountUid && bankAccounts.length > 0) setAccountUid(bankAccounts[0].uid);
  }, [bankAccounts, accountUid]);

  const total = useMemo(() => lines.reduce((acc, l) => acc + (Number(l.amount) || 0), 0), [lines]);

  const run = async () => {
    if (!accountUid) { setBanner({ kind: 'err', msg: 'Pick a bank account.' }); return; }
    const nonEmpty = lines.filter((l) => Number(l.amount) > 0);
    if (nonEmpty.length === 0) { setBanner({ kind: 'err', msg: 'Add at least one statement line with an amount.' }); return; }
    setBusy(true);
    const r = await reconcile({
      bank_account_uid: accountUid,
      period_start: periodStart,
      period_end: periodEnd,
      statement_balance: Number(statementBalance) || 0,
      lines: nonEmpty.map((l) => ({ date: l.date, amount: Number(l.amount), reference: l.reference || '' })),
    });
    setBusy(false);
    if (r) {
      setBanner({ kind: 'ok', msg: `Reconciled: ${r.matched} matched, ${r.unmatched} unmatched.` });
      onCreated(r);
    } else {
      setBanner({ kind: 'err', msg: 'Failed to reconcile.' });
    }
  };

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex items-center gap-3">
        <button onClick={() => navigate('/finance/banking')} className="flex items-center gap-1 text-sm font-bold text-text-muted hover:text-text">
          <ArrowLeft size={16} /> Back to Banking
        </button>
      </div>

      <div className="bg-card border border-border rounded-2xl p-6 shadow-sm">
        <h1 className="text-3xl font-extrabold text-text tracking-tight">New reconciliation session</h1>
        <p className="text-text-muted mt-1 text-lg">Paste (or type) your statement lines, then reconcile.</p>
      </div>

      {banner && (
        <div className={`rounded-2xl border p-4 flex items-center gap-3 text-sm ${
          banner.kind === 'ok'
            ? 'bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-950/30 dark:border-emerald-900 dark:text-emerald-300'
            : 'bg-red-50 border-red-200 text-red-700 dark:bg-red-950/30 dark:border-red-900 dark:text-red-300'
        }`}>
          {banner.kind === 'ok' ? <CheckCircle2 size={18} /> : <AlertCircle size={18} />}
          <span className="flex-1">{banner.msg}</span>
          <button onClick={() => setBanner(null)} className="text-xs font-bold underline">Dismiss</button>
        </div>
      )}

      <div className="bg-card border border-border rounded-2xl p-5 shadow-sm space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Account</span>
            <select value={accountUid} onChange={(e) => setAccountUid(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">
              {bankAccounts.length === 0 ? <option>No bank accounts available</option> : null}
              {bankAccounts.map((b) => <option key={b.uid} value={b.uid}>{b.name} · {b.currency}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Period start</span>
            <input type="date" value={periodStart} onChange={(e) => setPeriodStart(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>
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Period end</span>
            <input type="date" value={periodEnd} onChange={(e) => setPeriodEnd(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>
        </div>
        <label className="block">
          <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Statement closing balance</span>
          <input type="number" step="0.01" value={statementBalance} onChange={(e) => setStatementBalance(e.target.value)} className="mt-1 w-full md:w-1/3 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>
      </div>

      <div className="bg-card border border-border rounded-2xl 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">Statement lines</h3>
          <button onClick={() => setLines((l) => [...l, { date: new Date().toISOString().slice(0, 10), amount: '', reference: '' }])} className="flex items-center gap-1 text-xs font-bold text-primary hover:underline">
            <Plus size={12} /> Add line
          </button>
        </div>
        <table className="w-full text-left">
          <thead className="bg-card">
            <tr>
              <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Date</th>
              <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Amount</th>
              <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Reference</th>
              <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {lines.map((l, i) => (
              <tr key={i}>
                <td className="px-4 py-2">
                  <input type="date" value={l.date} onChange={(e) => setLines((arr) => arr.map((x, j) => j === i ? { ...x, date: e.target.value } : x))} className="w-full px-2 py-1.5 bg-muted/30 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
                </td>
                <td className="px-4 py-2">
                  <input type="number" step="0.01" value={l.amount} onChange={(e) => setLines((arr) => arr.map((x, j) => j === i ? { ...x, amount: e.target.value } : x))} className="w-full text-right px-2 py-1.5 bg-muted/30 border border-border rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary/30" />
                </td>
                <td className="px-4 py-2">
                  <input type="text" value={l.reference} onChange={(e) => setLines((arr) => arr.map((x, j) => j === i ? { ...x, reference: e.target.value } : x))} className="w-full px-2 py-1.5 bg-muted/30 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
                </td>
                <td className="px-4 py-2 text-right">
                  <button onClick={() => setLines((arr) => arr.filter((_, j) => j !== i))} className="p-1.5 rounded-md hover:bg-red-500 hover:text-white text-text-muted transition-all" title="Remove line" aria-label="Remove line">
                    <Trash2 size={14} />
                  </button>
                </td>
              </tr>
            ))}
            <tr>
              <td className="px-4 py-3 text-right text-xs font-bold text-text-muted uppercase tracking-widest">Total</td>
              <td className="px-4 py-3 text-right font-bold text-text font-mono">{currency(total)}</td>
              <td colSpan={2} />
            </tr>
          </tbody>
        </table>
        <div className="px-6 py-4 border-t border-border bg-muted/30 flex justify-end gap-2">
          <button onClick={() => navigate('/finance/banking')} 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={run} disabled={busy} 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" /> : <Scale size={14} />}
            <span>Run reconciliation</span>
          </button>
        </div>
      </div>

      <div className="bg-card border border-border rounded-2xl overflow-hidden shadow-sm">
        <div className="px-6 py-4 border-b border-border bg-muted/30">
          <h3 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">Recent sessions</h3>
        </div>
        <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">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.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">
                  <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${statusBadge(r.status)}`}>{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">
                    <Save size={12} /> Review
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DetailMode({
  reconciliation, loading, navigate, resolve,
}: {
  reconciliation: Reconciliation | null;
  loading: boolean;
  navigate: ReturnType<typeof useNavigate>;
  resolve: (line_id: number, action: 'ignore' | 'attach', payment_id?: number) => Promise<{ success: boolean; unmatched_count: number } | null>;
}) {
  const unmatched = reconciliation?.lines?.filter((l) => l.match_status === 'unmatched') || [];
  const matched = reconciliation?.lines?.filter((l) => l.match_status === 'matched') || [];
  const ignored = reconciliation?.lines?.filter((l) => l.match_status === 'ignored') || [];

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex items-center gap-3">
        <button onClick={() => navigate('/finance/banking')} className="flex items-center gap-1 text-sm font-bold text-text-muted hover:text-text">
          <ArrowLeft size={16} /> Back to Banking
        </button>
      </div>
      {loading && !reconciliation ? (
        <div className="flex justify-center items-center h-[40vh]"><Loader2 className="animate-spin text-text-muted" /></div>
      ) : !reconciliation ? (
        <div className="bg-card border border-border rounded-2xl p-10 text-center text-text-muted">Reconciliation not found.</div>
      ) : (
        <>
          <div className="bg-card border border-border rounded-2xl p-6 shadow-sm">
            <div className="flex flex-col md:flex-row md:items-end justify-between gap-3">
              <div>
                <p className="text-[0.6rem] uppercase font-black tracking-[2px] text-primary">Reconciliation session</p>
                <h1 className="text-2xl font-black text-text mt-1">{reconciliation.account_name}</h1>
                <p className="text-[0.85rem] text-text-muted mt-1">
                  {reconciliation.period_start} → {reconciliation.period_end}
                </p>
              </div>
              <div className="flex items-center gap-4">
                <div className="text-right">
                  <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">Statement</p>
                  <p className="text-lg font-black">{currency(Number(reconciliation.statement_balance))}</p>
                </div>
                <div className="text-right">
                  <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">Book</p>
                  <p className="text-lg font-black">{currency(Number(reconciliation.book_balance || 0))}</p>
                </div>
                <span className={`text-[0.65rem] font-black uppercase tracking-tight px-2.5 py-1 rounded-full border ${statusBadge(reconciliation.status)}`}>{reconciliation.status}</span>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-3 gap-3">
            <Tile label="Matched" value={matched.length} tone="emerald" />
            <Tile label="Unmatched" value={unmatched.length} tone={unmatched.length === 0 ? 'emerald' : 'rose'} />
            <Tile label="Ignored" value={ignored.length} />
          </div>

          {unmatched.length > 0 && (
            <div className="bg-card border border-rose-200 rounded-2xl overflow-hidden shadow-sm">
              <div className="px-6 py-4 border-b border-rose-200 bg-rose-50 flex items-center gap-2">
                <XCircle size={16} className="text-rose-500" />
                <h3 className="text-[0.65rem] font-black uppercase tracking-[2px] text-rose-700">Unmatched statement lines — resolve each</h3>
              </div>
              <table className="w-full text-left">
                <thead className="bg-card">
                  <tr>
                    <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Date</th>
                    <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Amount</th>
                    <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Reference</th>
                    <th className="px-4 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">
                  {unmatched.map((l) => (
                    <tr key={l.id} className="hover:bg-muted/30 transition-colors">
                      <td className="px-4 py-3 text-[0.85rem] font-mono text-text-secondary">{l.statement_date || '—'}</td>
                      <td className="px-4 py-3 text-right text-[0.85rem] font-mono font-bold text-rose-600">{currency(Number(l.statement_amount))}</td>
                      <td className="px-4 py-3 text-[0.85rem] text-text-secondary">{l.statement_reference || '—'}</td>
                      <td className="px-4 py-3 text-right">
                        <button
                          onClick={() => resolve(l.id, 'ignore')}
                          className="px-2.5 py-1 rounded-md border border-border text-xs font-bold hover:bg-muted transition-all"
                        >
                          Ignore
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {(matched.length > 0 || ignored.length > 0) && (
            <div className="bg-card border border-border rounded-2xl overflow-hidden shadow-sm">
              <div className="px-6 py-4 border-b border-border bg-muted/30 flex items-center gap-2">
                <CheckCircle2 size={16} className="text-emerald-500" />
                <h3 className="text-[0.65rem] font-black uppercase tracking-[2px] text-emerald-700">Reconciled / ignored lines ({matched.length + ignored.length})</h3>
              </div>
              <table className="w-full text-left">
                <thead className="bg-card">
                  <tr>
                    <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Date</th>
                    <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Amount</th>
                    <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Reference</th>
                    <th className="px-4 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {[...matched, ...ignored].map((l) => (
                    <tr key={l.id} className="hover:bg-muted/30 transition-colors">
                      <td className="px-4 py-3 text-[0.85rem] font-mono text-text-secondary">{l.statement_date || '—'}</td>
                      <td className="px-4 py-3 text-right text-[0.85rem] font-mono">{currency(Number(l.statement_amount))}</td>
                      <td className="px-4 py-3 text-[0.85rem] text-text-secondary">{l.statement_reference || '—'}</td>
                      <td className="px-4 py-3">
                        <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${matchBadge(l.match_status)}`}>{l.match_status}</span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </>
      )}
    </div>
  );
}

function Tile({ label, value, tone }: { label: string; value: 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">
      <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">{label}</p>
      <p className={`text-2xl font-black mt-1 ${colorCls}`}>{value}</p>
    </div>
  );
}
