/**
 * Admin Dashboard (school_admin / systems_admin)
 *
 * Consumes /api/dashboard/admin via useDashboardStore. Layout:
 *   1. KPI tiles (active_enrollments, attendance_rate_30d, programs_count, users_by_role)
 *   2. Recharts BarChart of grade_distribution (A/B/C/D/F)
 *   3. Legacy "schools today" summary using the existing stats block
 *      (today's attendance, pending fees, total classes) so the page still
 *      gives admins something useful when the new analytics are sparse.
 *
 * Access denied state (HTTP 401/403 from the backend) renders a dedicated
 * panel instead of the layout so a student / teacher / parent who navigates
 * here directly sees "Access denied" rather than an empty admin shell.
 */

import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Users, GraduationCap, BookOpen, TrendingUp,
  AlertCircle, ShieldX, BarChart3, Activity, Layers, RefreshCw, Database, HardDrive,
} from 'lucide-react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell, LabelList,
} from 'recharts';
import { useDashboardStore } from '../../store/dashboard';
import { useEducationTerms } from '../../utils/educationTerms';

const GRADE_COLORS: Record<string, string> = {
  A: '#10b981', // emerald-500
  B: '#3b82f6', // blue-500
  C: '#f59e0b', // amber-500
  D: '#f97316', // orange-500
  F: '#ef4444', // red-500
};

export default function AdminDashboard() {
  const navigate = useNavigate();
  const terms = useEducationTerms();
  const {
    admin, loading, error, accessDenied, fetchAdmin,
    infrastructureHealth, fetchInfrastructureHealth,
    gradeDistributionBySubject, fetchGradeDistributionBySubject,
  } = useDashboardStore();

  useEffect(() => {
    fetchAdmin();
    fetchInfrastructureHealth();
    fetchGradeDistributionBySubject(8);
  }, [fetchAdmin, fetchInfrastructureHealth, fetchGradeDistributionBySubject]);

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

  if (accessDenied) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
        <ShieldX size={56} className="text-red-500" />
        <h2 className="text-2xl font-extrabold text-text">Access denied</h2>
        <p className="text-text-muted text-sm max-w-md text-center">
          {error || 'You do not have permission to view the admin dashboard. This page is restricted to school administrators.'}
        </p>
        <button
          onClick={() => navigate('/dashboard/admin')}
          className="px-4 py-2 bg-primary text-white rounded-xl hover:opacity-90"
        >
          Go back
        </button>
      </div>
    );
  }

  if (error && !admin) {
    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 dashboard data.</p>
        <p className="text-sm text-text-muted">{error}</p>
        <button
          onClick={() => fetchAdmin()}
          className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-xl"
        >
          <RefreshCw size={16} /> Retry
        </button>
      </div>
    );
  }

  if (!admin) return null;

  // Build KPI values from new analytics shape
  const totalUsersByRole = Object.values(admin.users_by_role || {}).reduce((a, b) => a + b, 0);
  const totalTeachers = admin.users_by_role?.teacher || 0;
  const totalStudents = admin.users_by_role?.student || 0;

  const kpis = [
    {
      label: 'Active Enrollments',
      value: admin.active_enrollments.toLocaleString(),
      icon: GraduationCap,
      color: 'blue',
      subtext: 'Currently enrolled students',
    },
    {
      label: 'Attendance (30d)',
      value: `${admin.attendance_rate_30d}%`,
      icon: TrendingUp,
      color: admin.attendance_rate_30d >= 90 ? 'emerald' : admin.attendance_rate_30d >= 75 ? 'blue' : 'orange',
      subtext: 'Average over the last 30 days',
    },
    {
      label: 'Programs',
      value: admin.programs_count.toLocaleString(),
      icon: BookOpen,
      color: 'indigo',
      subtext: `${terms.subjects} on offer`,
    },
    {
      label: 'Users',
      value: totalUsersByRole.toLocaleString(),
      icon: Users,
      color: 'purple',
      subtext: `${totalStudents} students • ${totalTeachers} teachers`,
    },
  ];

  const chartData = [
    { grade: 'A', count: admin.grade_distribution.A, fill: GRADE_COLORS.A },
    { grade: 'B', count: admin.grade_distribution.B, fill: GRADE_COLORS.B },
    { grade: 'C', count: admin.grade_distribution.C, fill: GRADE_COLORS.C },
    { grade: 'D', count: admin.grade_distribution.D, fill: GRADE_COLORS.D },
    { grade: 'F', count: admin.grade_distribution.F, fill: GRADE_COLORS.F },
  ];
  const gradeTotal = admin.grade_distribution.total;

  // Users by role: top roles (excluding legacy/empty)
  const roleEntries = Object.entries(admin.users_by_role || {})
    .filter(([, c]) => c > 0)
    .sort((a, b) => b[1] - a[1]);

  return (
    <div className="space-y-8 animate-in fade-in duration-500">
      {/* Header */}
      <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">Admin Dashboard</h1>
          <p className="text-text-muted mt-1 text-lg">School-wide analytics at a glance.</p>
        </div>
        <button
          onClick={() => fetchAdmin()}
          className="flex items-center gap-2 px-4 py-2 bg-card border border-border text-text rounded-xl text-sm font-semibold hover:border-primary hover:text-primary transition-all"
        >
          <RefreshCw size={16} />
          Refresh
        </button>
      </div>

      {/* KPI Tiles */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpis.map((kpi) => (
          <div
            key={kpi.label}
            className="bg-card p-6 rounded-2xl border border-border hover:shadow-md transition-all"
          >
            <div className="flex justify-between items-start mb-4">
              <div className={`p-2.5 rounded-xl bg-muted text-primary`}>
                <kpi.icon size={22} />
              </div>
              <div className={`flex items-center gap-1 text-[0.7rem] font-bold px-2 py-1 rounded-full bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400`}>
                <Activity size={12} />
                Live
              </div>
            </div>
            <p className="text-xs font-bold uppercase tracking-wider text-text-muted">
              {kpi.label}
            </p>
            <h3 className="text-3xl font-black mt-1 tracking-tight">{kpi.value}</h3>
            <p className="text-[0.65rem] mt-2 italic font-medium text-text-muted">
              {kpi.subtext}
            </p>
          </div>
        ))}
      </div>

      {/* Main Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Grade Distribution Chart */}
        <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 flex justify-between items-center bg-muted/50">
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
              Grade Distribution (90d)
            </h4>
            <span className="text-[0.7rem] font-bold text-text-muted">
              {gradeTotal.toLocaleString()} graded marks
            </span>
          </div>
          <div className="p-6">
            <div className="h-72 w-full">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={chartData} margin={{ top: 20, right: 10, left: 0, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="rgba(148,163,184,0.2)" />
                  <XAxis dataKey="grade" tick={{ fill: 'currentColor', fontSize: 12, fontWeight: 700 }} />
                  <YAxis allowDecimals={false} tick={{ fill: 'currentColor', fontSize: 12 }} />
                  <Tooltip
                    cursor={{ fill: 'currentColor', className: 'text-muted/10' }}
                    contentStyle={{ backgroundColor: 'var(--card)', border: '1px solid var(--border)', borderRadius: 12, color: 'var(--text)' }}
                    labelStyle={{ color: 'var(--text-light)', fontWeight: 700 }}
                    formatter={(value: number) => [value, 'Marks']}
                  />
                  <Bar dataKey="count" radius={[8, 8, 0, 0]}>
                    {chartData.map((entry) => (
                      <Cell key={entry.grade} fill={entry.fill} />
                    ))}
                    <LabelList dataKey="count" position="top" style={{ fill: 'currentColor', fontSize: 12, fontWeight: 700 }} />
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </div>
            <div className="mt-4 grid grid-cols-2 sm:grid-cols-5 gap-2 text-center">
              {chartData.map((d) => (
                <div key={d.grade} className="bg-muted/50 rounded-xl px-2 py-2 border border-border">
                  <p className="text-[0.6rem] font-black uppercase tracking-widest" style={{ color: d.fill }}>
                    {d.grade}
                  </p>
                  <p className="text-base font-black text-text">{d.count}</p>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Users by Role + Today's Snapshot */}
        <div className="space-y-6">
          <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 items-center gap-2">
              <Layers size={14} className="text-primary" />
              <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
                Users by Role
              </h4>
            </div>
            <div className="p-4 space-y-2">
              {roleEntries.length === 0 ? (
                <p className="text-sm text-text-muted text-center py-6">No users yet.</p>
              ) : (
                roleEntries.map(([role, count]) => (
                  <div key={role} className="flex items-center justify-between p-3 bg-muted/40 rounded-xl border border-border">
                    <span className="text-xs font-bold text-text capitalize">{role.replace(/_/g, ' ')}</span>
                    <span className="px-3 py-1 rounded-full bg-primary/10 text-primary text-xs font-black">
                      {count.toLocaleString()}
                    </span>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Legacy "today's pulse" — keeps the page useful when new analytics are sparse */}
          {admin.stats && (
            <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 items-center gap-2">
                <BarChart3 size={14} className="text-primary" />
                <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
                   Today at a Glance
                </h4>
              </div>
              <div className="p-4 grid grid-cols-2 gap-3">
                <div className="p-4 bg-emerald-50/50 dark:bg-emerald-950/20 border border-emerald-100 dark:border-emerald-900/30 rounded-xl">
                  <p className="text-[0.55rem] uppercase font-black tracking-widest text-emerald-600 dark:text-emerald-400">Attendance</p>
                  <p className="text-xl font-black text-emerald-700 dark:text-emerald-300 mt-1">
                    {admin.stats.todayAttendance.total > 0
                      ? Math.round((admin.stats.todayAttendance.present / admin.stats.todayAttendance.total) * 100)
                      : 0}
                    %
                  </p>
                  <p className="text-[0.6rem] text-text-muted mt-1">
                    {admin.stats.todayAttendance.present}/{admin.stats.todayAttendance.total}
                  </p>
                </div>
                <div className="p-4 bg-orange-50/50 dark:bg-orange-950/20 border border-orange-100 dark:border-orange-900/30 rounded-xl">
                  <p className="text-[0.55rem] uppercase font-black tracking-widest text-orange-600 dark:text-orange-400">Pending Fees</p>
                  <p className="text-xl font-black text-orange-700 dark:text-orange-300 mt-1">
                    ${admin.stats.pendingFees.toLocaleString()}
                  </p>
                  <p className="text-[0.6rem] text-text-muted mt-1">outstanding</p>
                </div>
                <div className="p-4 bg-blue-50/50 dark:bg-blue-950/20 border border-blue-100 dark:border-blue-900/30 rounded-xl">
                  <p className="text-[0.55rem] uppercase font-black tracking-widest text-blue-600 dark:text-blue-400">Classes</p>
                  <p className="text-xl font-black text-blue-700 dark:text-blue-300 mt-1">
                    {admin.classes_count}
                  </p>
                  <p className="text-[0.6rem] text-text-muted mt-1">active</p>
                </div>
                <div className="p-4 bg-purple-50/50 dark:bg-purple-950/20 border border-purple-100 dark:border-purple-900/30 rounded-xl">
                  <p className="text-[0.55rem] uppercase font-black tracking-widest text-purple-600 dark:text-purple-400">Revenue</p>
                  <p className="text-xl font-black text-purple-700 dark:text-purple-300 mt-1">
                    ${admin.stats.totalRevenue.toLocaleString()}
                  </p>
                  <p className="text-[0.6rem] text-text-muted mt-1">all time</p>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    {/* Per-subject grade distribution + Infrastructure health */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <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 flex justify-between items-center bg-muted/50">
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
              Per-{terms.subject} Grade Distribution
            </h4>
            <span className="text-[0.7rem] font-bold text-text-muted">
              top {gradeDistributionBySubject.length} subjects
            </span>
          </div>
          <div className="p-6">
            {gradeDistributionBySubject.length === 0 ? (
              <div className="py-10 text-center text-text-muted text-sm">No grades yet.</div>
            ) : (
              <div className="space-y-3">
                {gradeDistributionBySubject.map((s) => {
                  const total = s.total;
                  const widthA = total ? (s.distribution.A / total) * 100 : 0;
                  const widthB = total ? (s.distribution.B / total) * 100 : 0;
                  const widthC = total ? (s.distribution.C / total) * 100 : 0;
                  const widthD = total ? (s.distribution.D / total) * 100 : 0;
                  const widthF = total ? (s.distribution.F / total) * 100 : 0;
                  return (
                    <div key={s.subject_id}>
                      <div className="flex justify-between items-center mb-1">
                        <p className="text-xs font-bold text-text truncate">{s.subject_name}</p>
                        <p className="text-[0.65rem] text-text-muted font-black">
                          {s.avg_pct}% avg • {total} marks
                        </p>
                      </div>
                      <div className="h-3 w-full bg-muted rounded-full overflow-hidden flex border border-border">
                        <div style={{ width: `${widthA}%` }} className="bg-emerald-500" />
                        <div style={{ width: `${widthB}%` }} className="bg-blue-500" />
                        <div style={{ width: `${widthC}%` }} className="bg-amber-500" />
                        <div style={{ width: `${widthD}%` }} className="bg-orange-500" />
                        <div style={{ width: `${widthF}%` }} className="bg-red-500" />
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        <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 items-center gap-2">
            <HardDrive size={14} className="text-primary" />
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
              Infrastructure Health
            </h4>
          </div>
          <div className="p-4 space-y-3">
            <div className="p-3 bg-muted/40 rounded-xl border border-border">
              <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted">Database Size</p>
              <p className="text-2xl font-black text-text flex items-center gap-2">
                <Database size={16} className="text-primary" />
                {infrastructureHealth?.db_size_mb ?? '—'}
                <span className="text-sm font-medium text-text-muted">MB</span>
              </p>
              <p className="text-[0.6rem] text-text-muted">
                {infrastructureHealth?.db_size_bytes
                  ? `${infrastructureHealth.db_size_bytes.toLocaleString()} bytes`
                  : 'Loading...'}
              </p>
            </div>
            <div className="p-3 bg-muted/40 rounded-xl border border-border">
              <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted">Sync Queue</p>
              <div className="flex items-baseline gap-3 mt-1">
                <p className="text-2xl font-black text-orange-600">
                  {infrastructureHealth?.sync_queue.pending ?? '—'}
                </p>
                <p className="text-[0.65rem] text-text-muted">pending</p>
                <p className="text-sm font-black text-emerald-600 ml-auto">
                  {infrastructureHealth?.sync_queue.synced ?? '—'}
                </p>
                <p className="text-[0.65rem] text-text-muted">synced</p>
              </div>
              <div className="mt-2 w-full bg-muted rounded-full h-2 overflow-hidden border border-border">
                {(() => {
                  const total = (infrastructureHealth?.sync_queue.pending || 0) + (infrastructureHealth?.sync_queue.synced || 0);
                  const pct = total > 0 ? ((infrastructureHealth?.sync_queue.synced || 0) / total) * 100 : 0;
                  return <div className="bg-emerald-500 h-full transition-all" style={{ width: `${pct}%` }} />;
                })()}
              </div>
            </div>
            {infrastructureHealth?.table_rows && (
              <div className="p-3 bg-muted/40 rounded-xl border border-border">
                <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted mb-2">Top Tables</p>
                <div className="grid grid-cols-2 gap-1.5">
                  {Object.entries(infrastructureHealth.table_rows)
                    .filter(([, v]) => v != null)
                    .slice(0, 8)
                    .map(([t, c]) => (
                      <div key={t} className="flex justify-between text-[0.6rem]">
                        <span className="text-text-muted truncate">{t}</span>
                        <span className="font-black text-text">{c?.toLocaleString()}</span>
                      </div>
                    ))}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
