import { useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  ResponsiveContainer, AreaChart, Area, XAxis, YAxis,
  Tooltip, CartesianGrid,
} from 'recharts';
import {
  Wallet, AlertCircle, Receipt, ClipboardList, Plus,
  CircleDollarSign, TrendingUp, FileText, Filter, Scale,
} from 'lucide-react';
import { useFinanceStore, EXPENSE_CATEGORIES } from '../../store/finance';
import { useAuthStore } from '../../store/auth';

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

export default function FinanceDashboard() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const {
    dashboardSummary,
    expenses,
    loading,
    error,
    fetchDashboardSummary,
    fetchExpenses,
  } = useFinanceStore();

  useEffect(() => {
    fetchDashboardSummary();
    // top 5 recent expenses for the panel
    fetchExpenses({ limit: 5, offset: 0, status: undefined, category: undefined });
  }, [fetchDashboardSummary, fetchExpenses]);

  const recentExpenses = useMemo(
    () => (expenses || []).slice(0, 5),
    [expenses],
  );

  // Build the small chart series — when the backend hasn't given us a monthly
  // series endpoint yet (TODO Phase 2), we synthesise a 2-point series from
  // `expenses_mtd` and `collected_mtd` to give the tile a visible shape.
  const trendData = useMemo(() => {
    const sum = dashboardSummary;
    if (!sum) return [];
    const rev = sum.collected_mtd || 0;
    const exp = sum.expenses_mtd || 0;
    return [
      { label: 'Start of month', revenue: 0, expenses: 0 },
      { label: 'Now', revenue: rev, expenses: exp },
    ];
  }, [dashboardSummary]);

  if (!dashboardSummary) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
        <div className="w-12 h-12 border-4 border-emerald-600 border-t-transparent rounded-full animate-spin" />
        <p className="font-medium animate-pulse">Loading Finance dashboard…</p>
      </div>
    );
  }

  if (error && !dashboardSummary) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
        <AlertCircle size={48} className="text-red-500" />
        <p className="text-text-muted font-medium">Unable to load Finance dashboard.</p>
        <p className="text-sm text-text-muted">{error}</p>
        <button
          onClick={() => fetchDashboardSummary()}
          className="px-4 py-2 bg-primary text-white rounded-xl"
        >
          Retry
        </button>
      </div>
    );
  }

  const s = dashboardSummary!;
  const cards = [
    {
      label: 'Collected MTD',
      value: currency(s.collected_mtd),
      icon: CircleDollarSign,
      sub: 'Paid student fees this month',
      color: 'emerald',
      path: '/fees',
    },
    {
      label: 'Outstanding Fees',
      value: currency(s.outstanding_fees),
      icon: Wallet,
      sub: `${s.installments_due_14d || 0} due in next 14 days`,
      color: 'orange',
      path: '/fees',
    },
    {
      label: 'Expenses MTD',
      value: currency(s.expenses_mtd),
      icon: TrendingUp,
      sub: `${s.pending_expenses} pending approval`,
      color: 'blue',
      path: '/finance/expenses',
    },
    {
      label: 'Payroll',
      value: s.payroll_last_run ? s.payroll_last_run.period : '—',
      icon: ClipboardList,
      sub: s.payroll_last_run ? `Status: ${s.payroll_last_run.status}` : 'No runs yet',
      color: 'primary',
      path: '/finance/payroll/runs',
    },
  ];

  // §10c — second tile row for the operational back-office.
  const opsCards = [
    {
      label: 'Open invoices',
      value: s.open_invoices || 0,
      icon: FileText,
      sub: `${s.overdue_invoices || 0} overdue`,
      color: s.overdue_invoices ? 'orange' : 'emerald',
      path: '/finance/invoices',
    },
    {
      label: 'Trips next 30d',
      value: s.upcoming_trips_30d || 0,
      icon: ClipboardList,
      sub: 'Published & not yet departed',
      color: 'blue',
      path: '/finance/trips',
    },
    {
      label: 'Reconciliations',
      value: s.pending_reconciliations || 0,
      icon: Scale,
      sub: 'Sessions with discrepancies',
      color: s.pending_reconciliations ? 'rose' : 'emerald',
      path: '/finance/banking',
    },
    {
      label: 'Student groups',
      value: s.student_groups_count || 0,
      icon: Filter,
      sub: 'Bus routes, hostels, fee cohorts',
      color: 'primary',
      path: '/finance/groups',
    },
  ];

  return (
    <div className="space-y-8 animate-in fade-in duration-500">
      <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">
            Finance Dashboard
          </h1>
          <p className="text-text-muted mt-1 text-lg">
            Welcome, {user?.first_name || 'Finance'}. Cash flow at a glance.
          </p>
        </div>
        <button
          onClick={() => navigate('/finance/expenses')}
          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={20} />
          <span>New Expense</span>
        </button>
      </div>

      {/* Stat cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {cards.map((card) => (
          <div
            key={card.label}
            onClick={() => navigate(card.path)}
            className="p-6 rounded-2xl border bg-card border-border transition-all duration-300 hover:shadow-md cursor-pointer"
          >
            <div className="flex justify-between items-start mb-4">
              <div className="p-2.5 rounded-xl bg-muted text-[#0047AB]">
                <card.icon size={22} />
              </div>
            </div>
            <p className="text-xs font-bold uppercase tracking-wider text-text-muted">
              {card.label}
            </p>
            <h3 className="text-3xl font-black mt-1 tracking-tight">{card.value}</h3>
            <p className="text-[0.65rem] mt-2 italic font-medium text-text-muted">
              {card.sub}
            </p>
          </div>
        ))}
      </div>

      {/* §10c — Operational back-office tiles (Phase 2) */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {opsCards.map((card) => (
          <div
            key={card.label}
            onClick={() => navigate(card.path)}
            className="p-6 rounded-2xl border bg-card border-border transition-all duration-300 hover:shadow-md cursor-pointer"
          >
            <div className="flex justify-between items-start mb-4">
              <div className="p-2.5 rounded-xl bg-muted text-primary">
                <card.icon size={22} />
              </div>
            </div>
            <p className="text-xs font-bold uppercase tracking-wider text-text-muted">{card.label}</p>
            <h3 className="text-2xl font-black mt-1 tracking-tight">{card.value}</h3>
            <p className="text-[0.65rem] mt-2 italic font-medium text-text-muted">{card.sub}</p>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Chart panel */}
        <div className="lg:col-span-2 bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
          <div className="px-6 py-4 border-b border-border bg-muted/50">
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
              Revenue vs Expenses — month to date
            </h4>
          </div>
          <div className="p-6 h-72">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={trendData} margin={{ top: 8, right: 16, left: 0, bottom: 0 }}>
                <defs>
                  <linearGradient id="revFill" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#10b981" stopOpacity={0.5} />
                    <stop offset="100%" stopColor="#10b981" stopOpacity={0.05} />
                  </linearGradient>
                  <linearGradient id="expFill" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#ef4444" stopOpacity={0.5} />
                    <stop offset="100%" stopColor="#ef4444" stopOpacity={0.05} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                <XAxis dataKey="label" tick={{ fontSize: 11 }} />
                <YAxis tick={{ fontSize: 11 }} />
                <Tooltip
                  contentStyle={{
                    background: '#0f172a',
                    border: '1px solid #1e293b',
                    borderRadius: 8,
                    color: '#fff',
                  }}
                  labelStyle={{ color: '#fff', fontWeight: 700 }}
                  formatter={(v: number) => currency(v)}
                />
                <Area
                  type="monotone"
                  dataKey="revenue"
                  stroke="#10b981"
                  fill="url(#revFill)"
                  strokeWidth={2}
                  name="Revenue"
                />
                <Area
                  type="monotone"
                  dataKey="expenses"
                  stroke="#ef4444"
                  fill="url(#expFill)"
                  strokeWidth={2}
                  name="Expenses"
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
          <div className="px-6 pb-4 text-[0.65rem] text-text-muted italic">
            {/* TODO Phase 2: replace with monthly revenue / expenses time-series from `/api/finance/dashboard/summary` (currently aggregate-only). */}
            Aggregate MTD view. A true monthly series endpoint is planned for Phase 2.
          </div>
        </div>

        {/* Quick links panel */}
        <div className="bg-card rounded-2xl border border-border p-6 shadow-sm">
          <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary mb-6">
            Quick actions
          </h4>
          <div className="grid grid-cols-2 gap-3">
            {[
              { label: 'New Expense', icon: Plus, path: '/finance/expenses' },
              { label: 'Expenses List', icon: Receipt, path: '/finance/expenses' },
              { label: 'Payroll', icon: ClipboardList, path: '/finance/payroll/runs' },
              { label: 'Fees', icon: Wallet, path: '/fees' },
            ].map((q) => (
              <button
                key={q.label}
                onClick={() => navigate(q.path)}
                className="flex flex-col items-center justify-center p-4 bg-muted/50 hover:bg-primary hover:text-white rounded-2xl transition-all duration-300 group border border-border hover:border-transparent hover:shadow-lg hover:shadow-blue-900/10"
              >
                <div className="mb-2 p-2 rounded-xl group-hover:bg-white/10 transition-colors">
                  <q.icon size={20} />
                </div>
                <span className="text-[0.7rem] font-bold text-center leading-tight">{q.label}</span>
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Recent expenses table */}
      <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/50 flex justify-between items-center">
          <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
            Recent expenses (top 5)
          </h4>
          <button
            onClick={() => navigate('/finance/expenses')}
            className="text-primary text-[0.7rem] font-bold hover:underline"
          >
            View all expenses →
          </button>
        </div>
        <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">
                  Date
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Category
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Description
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Amount
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Status
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {recentExpenses.length > 0 ? (
                recentExpenses.map((e) => (
                  <tr key={e.id} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-4 text-[0.75rem] font-mono text-text-muted">
                      {(e.expense_date || '').slice(0, 10)}
                    </td>
                    <td className="px-6 py-4">
                      <span className="text-[0.7rem] font-bold uppercase tracking-tight px-2 py-1 rounded-md bg-muted text-text">
                        {(EXPENSE_CATEGORIES.find((c) => c.value === e.category) || { label: e.category }).label}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] font-medium text-text-secondary line-clamp-1">
                      {e.description}
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] font-bold text-text">
                      {currency(Number(e.amount))}
                    </td>
                    <td className="px-6 py-4">
                      <span className="text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full bg-muted text-text-muted">
                        {e.status}
                      </span>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={5} className="px-6 py-8 text-center text-text-muted text-sm">
                    No expenses recorded yet.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
