import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Wallet, AlertCircle, Receipt, ClipboardList,
  CircleDollarSign, Tag, Filter, Scale, FileText, Building2,
} from 'lucide-react';
import { useFinanceStore, EXPENSE_CATEGORIES } from '../../store/finance';
import { useFinanceEngineStore } from '../../store/finance-engine';
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 AccountantDashboard() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const { dashboardSummary, loading, error, fetchDashboardSummary, expenseSummary, fetchExpenseSummary } = useFinanceStore();
  const { fetchStudentGroups } = useFinanceEngineStore();

  useEffect(() => {
    fetchDashboardSummary();
    fetchExpenseSummary();
    fetchStudentGroups();
  }, [fetchDashboardSummary, fetchExpenseSummary, fetchStudentGroups]);

  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-primary border-t-transparent rounded-full animate-spin" />
        <p className="font-medium animate-pulse">Loading accountant 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-rose-500" />
        <p className="text-text-muted font-medium">Unable to load dashboard.</p>
        <p className="text-sm text-text-muted">{error}</p>
        <button onClick={() => { fetchDashboardSummary(); fetchExpenseSummary(); }} className="px-4 py-2 bg-primary text-white rounded-xl">Retry</button>
      </div>
    );
  }

  const s = dashboardSummary!;
  const recentExpenses = expenseSummary;

  const tiles = [
    { label: 'Outstanding Fees', value: currency(s.outstanding_fees), icon: Wallet, sub: `${s.installments_due_14d || 0} due in 14 days`, color: 'orange', path: '/fees' },
    { label: 'Open Invoices', value: s.open_invoices || 0, icon: FileText, sub: `${s.overdue_invoices || 0} overdue`, color: s.overdue_invoices ? 'rose' : 'emerald', path: '/finance/invoices' },
    { label: 'Plan Installments', value: s.installments_due_14d || 0, icon: CalendarDays, sub: 'Due in next 14 days', color: 'blue', path: '/finance/plans' },
    { label: 'Reconciliations', value: s.pending_reconciliations || 0, icon: Scale, sub: 'Sessions with discrepancies', color: s.pending_reconciliations ? 'rose' : 'emerald', path: '/finance/banking' },
  ];

  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">
            Accountant Dashboard
          </h1>
          <p className="text-text-muted mt-1 text-lg">
            Welcome, {user?.first_name || 'Accountant'}. Billing pipeline at a glance.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => navigate('/finance/invoices')} 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]">
            <Receipt size={18} />
            <span>Issue invoice</span>
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {tiles.map((t) => (
          <div key={t.label} onClick={() => navigate(t.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"><t.icon size={22} /></div>
            </div>
            <p className="text-xs font-bold uppercase tracking-wider text-text-muted">{t.label}</p>
            <h3 className="text-2xl font-black mt-1 tracking-tight">{t.value}</h3>
            <p className="text-[0.65rem] mt-2 italic font-medium text-text-muted">{t.sub}</p>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <button onClick={() => navigate('/finance/plans')} className="bg-card border border-border rounded-2xl p-6 shadow-sm text-left hover:shadow-md transition-all">
          <div className="flex items-center gap-2 mb-2">
            <ClipboardList size={18} className="text-primary" />
            <h3 className="text-lg font-black text-text">Payment Plans</h3>
          </div>
          <p className="text-sm text-text-muted">Materialise installment fees across class / group / single-student scope.</p>
        </button>
        <button onClick={() => navigate('/finance/discounts')} className="bg-card border border-border rounded-2xl p-6 shadow-sm text-left hover:shadow-md transition-all">
          <div className="flex items-center gap-2 mb-2">
            <Tag size={18} className="text-primary" />
            <h3 className="text-lg font-black text-text">Discounts</h3>
          </div>
          <p className="text-sm text-text-muted">Percent or fixed discounts at student / group / fee-group / universal level.</p>
        </button>
        <button onClick={() => navigate('/finance/groups')} className="bg-card border border-border rounded-2xl p-6 shadow-sm text-left hover:shadow-md transition-all">
          <div className="flex items-center gap-2 mb-2">
            <Filter size={18} className="text-primary" />
            <h3 className="text-lg font-black text-text">Student Groups</h3>
          </div>
          <p className="text-sm text-text-muted">Group by bus route, hostel, class, or any custom cut.</p>
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="bg-card border border-border rounded-2xl p-6 shadow-sm">
          <h3 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary mb-3">Expenses approval queue</h3>
          {recentExpenses ? (
            <div className="grid grid-cols-2 gap-3">
              <Tile label="Pending" value={recentExpenses.pending_count} tone="amber" />
              <Tile label="Pending amount" value={currency(recentExpenses.pending_amount)} tone="amber" />
              <Tile label="Approved this month" value={recentExpenses.approved_this_month.count} tone="emerald" />
              <Tile label="Approved total" value={currency(recentExpenses.approved_this_month.total)} tone="emerald" />
            </div>
          ) : (
            <p className="text-sm text-text-muted">Loading…</p>
          )}
          <button onClick={() => navigate('/finance/expenses')} className="mt-4 text-primary text-sm font-bold hover:underline">
            Open expenses list →
          </button>
        </div>

        <div className="bg-card border border-border rounded-2xl p-6 shadow-sm">
          <h3 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary mb-3">Latest activity</h3>
          <ul className="space-y-2 text-sm text-text-secondary">
            <li className="flex items-center gap-2"><Receipt size={14} className="text-emerald-600" /> {s.open_invoices || 0} invoices awaiting settlement</li>
            <li className="flex items-center gap-2"><Building2 size={14} className="text-blue-600" /> {s.student_groups_count || 0} student groups active</li>
            <li className="flex items-center gap-2"><Scale size={14} className="text-rose-600" /> {s.pending_reconciliations || 0} bank sessions need attention</li>
            <li className="flex items-center gap-2"><CircleDollarSign size={14} className="text-emerald-600" /> {currency(s.collected_mtd)} collected MTD</li>
          </ul>
        </div>
      </div>
    </div>
  );
}

function Tile({ label, value, tone }: { label: string; value: string | number; tone?: 'emerald' | 'amber' }) {
  const colorCls = tone === 'emerald' ? 'text-emerald-600' : tone === 'amber' ? 'text-amber-600' : 'text-text';
  return (
    <div className="bg-muted/30 rounded-xl p-3">
      <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">{label}</p>
      <p className={`text-lg font-black mt-1 ${colorCls}`}>{value}</p>
    </div>
  );
}

const CalendarDays = (props: { size?: number; className?: string }) => (
  <svg xmlns="http://www.w3.org/2000/svg" width={props.size || 24} height={props.size || 24} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className={props.className}>
    <rect width="18" height="18" x="3" y="4" rx="2" />
    <path d="M16 2v4M8 2v4M3 10h18" />
  </svg>
);
