import { useEffect, useState } from 'react';
import {
  Users,
  Wallet,
  Building2,
  CheckCircle2,
  Clock,
  GraduationCap,
  CreditCard,
} from 'lucide-react';
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';
import api from '../api/axios';
import StatCard from '../components/StatCard';
import { formatCurrency, roleLabels } from '../utils/format';

const PIE_COLORS = ['#1a78f2', '#f59e0b', '#10b981', '#8b5cf6', '#ec4899', '#06b6d4'];

export default function Dashboard() {
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api
      .get('/dashboard/stats')
      .then((res) => setStats(res.data))
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
        {[...Array(4)].map((_, i) => (
          <div key={i} className="h-32 animate-pulse rounded-2xl bg-slate-200" />
        ))}
      </div>
    );
  }

  const pieData =
    stats?.roleBreakdown?.map((r) => ({
      name: roleLabels[r.role] || r.role,
      value: r.count,
    })) || [];

  return (
    <div className="space-y-8">
      <div>
        <h1 className="font-display text-2xl font-bold text-slate-800">Dashboard</h1>
        <p className="text-slate-500">
          Overview for <span className="font-medium text-brand-600">{stats?.currentPeriod}</span>
        </p>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-6">
        <StatCard
          icon={Users}
          label="Active Staff"
          value={stats?.activeEmployees}
          sub={`${stats?.totalEmployees} total`}
          gradient="bg-gradient-to-br from-brand-600 to-brand-500"
        />
        <StatCard
          icon={Wallet}
          label="Monthly Payroll"
          value={formatCurrency(stats?.monthlyPayroll)}
          sub={stats?.currentPeriod}
          gradient="bg-gradient-to-br from-violet-600 to-purple-500"
        />
        <StatCard
          icon={GraduationCap}
          label="Active Students"
          value={stats?.activeStudents ?? 0}
          sub={`${stats?.studentPaymentCount ?? 0} payments`}
          gradient="bg-gradient-to-br from-sky-600 to-cyan-500"
        />
        <StatCard
          icon={CreditCard}
          label="Fees Collected"
          value={formatCurrency(stats?.studentFeesCollected ?? 0)}
          sub={`${stats?.pendingStudentPayments ?? 0} pending`}
          gradient="bg-gradient-to-br from-fuchsia-600 to-pink-500"
        />
        <StatCard
          icon={CheckCircle2}
          label="Paid Staff"
          value={stats?.paidThisMonth}
          sub={`${stats?.pendingThisMonth} pending`}
          gradient="bg-gradient-to-br from-emerald-600 to-teal-500"
        />
        <StatCard
          icon={Building2}
          label="Departments"
          value={stats?.departments}
          sub="Across school"
          gradient="bg-gradient-to-br from-amber-500 to-orange-500"
        />
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="card lg:col-span-2">
          <h3 className="font-display font-semibold text-slate-800">Payroll Trend (6 months)</h3>
          <p className="text-sm text-slate-500 mb-6">Gross vs net pay over time</p>
          <div className="h-72">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={stats?.chartData || []}>
                <defs>
                  <linearGradient id="gross" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#1a78f2" stopOpacity={0.3} />
                    <stop offset="95%" stopColor="#1a78f2" stopOpacity={0} />
                  </linearGradient>
                  <linearGradient id="net" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
                    <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                <XAxis dataKey="label" tick={{ fontSize: 12 }} stroke="#94a3b8" />
                <YAxis tick={{ fontSize: 12 }} stroke="#94a3b8" tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`} />
                <Tooltip formatter={(v) => formatCurrency(v)} />
                <Area type="monotone" dataKey="gross" stroke="#1a78f2" fill="url(#gross)" strokeWidth={2} name="Gross" />
                <Area type="monotone" dataKey="net" stroke="#10b981" fill="url(#net)" strokeWidth={2} name="Net" />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </div>

        <div className="card">
          <h3 className="font-display font-semibold text-slate-800">Staff by Role</h3>
          <p className="text-sm text-slate-500 mb-4">Active employees</p>
          <div className="h-56">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={pieData}
                  cx="50%"
                  cy="50%"
                  innerRadius={50}
                  outerRadius={80}
                  paddingAngle={3}
                  dataKey="value"
                >
                  {pieData.map((_, i) => (
                    <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <div className="mt-2 space-y-1">
            {pieData.map((d, i) => (
              <div key={d.name} className="flex items-center justify-between text-sm">
                <span className="flex items-center gap-2">
                  <span className="h-2.5 w-2.5 rounded-full" style={{ background: PIE_COLORS[i % PIE_COLORS.length] }} />
                  {d.name}
                </span>
                <span className="font-medium text-slate-700">{d.value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="card">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-display font-semibold text-slate-800">Recent Payroll</h3>
          <Clock className="h-5 w-5 text-slate-400" />
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-100 text-left text-slate-500">
                <th className="pb-3 font-medium">Employee</th>
                <th className="pb-3 font-medium">Period</th>
                <th className="pb-3 font-medium">Net Pay</th>
                <th className="pb-3 font-medium">Status</th>
              </tr>
            </thead>
            <tbody>
              {stats?.recentPayrolls?.map((p) => (
                <tr key={p._id} className="border-b border-slate-50 last:border-0">
                  <td className="py-3 font-medium text-slate-800">
                    {p.employee?.firstName} {p.employee?.lastName}
                    <span className="ml-2 text-xs text-slate-400">{p.employee?.employeeId}</span>
                  </td>
                  <td className="py-3 text-slate-600">{p.periodLabel}</td>
                  <td className="py-3 font-semibold text-emerald-600">{formatCurrency(p.netPay)}</td>
                  <td className="py-3">
                    <span
                      className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium capitalize ${
                        p.status === 'paid' ? 'bg-emerald-100 text-emerald-700' : 'bg-blue-100 text-blue-700'
                      }`}
                    >
                      {p.status}
                    </span>
                  </td>
                </tr>
              ))}
              {!stats?.recentPayrolls?.length && (
                <tr>
                  <td colSpan={4} className="py-8 text-center text-slate-400">
                    No payroll records yet
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      <div className="card">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-display font-semibold text-slate-800">Recent Student Payments</h3>
          <CreditCard className="h-5 w-5 text-slate-400" />
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-100 text-left text-slate-500">
                <th className="pb-3 font-medium">Student</th>
                <th className="pb-3 font-medium">Receipt</th>
                <th className="pb-3 font-medium">Type</th>
                <th className="pb-3 font-medium">Amount</th>
              </tr>
            </thead>
            <tbody>
              {stats?.recentStudentPayments?.map((p) => (
                <tr key={p._id} className="border-b border-slate-50 last:border-0">
                  <td className="py-3 font-medium text-slate-800">
                    {p.student?.firstName} {p.student?.lastName}
                    <span className="ml-2 text-xs text-slate-400">{p.student?.studentId}</span>
                  </td>
                  <td className="py-3 text-slate-600 font-mono text-xs">{p.receiptNumber}</td>
                  <td className="py-3 text-slate-600 capitalize">{p.paymentType}</td>
                  <td className="py-3 font-semibold text-violet-600">{formatCurrency(p.amount)}</td>
                </tr>
              ))}
              {!stats?.recentStudentPayments?.length && (
                <tr>
                  <td colSpan={4} className="py-8 text-center text-slate-400">
                    No student payments yet
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
