"use client";

import React, { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import {
  UserCheck,
  BookOpen,
  CalendarCheck,
  Calendar,
  Clock,
  ArrowRight,
  Eye,
  Settings,
  FileSpreadsheet,
  ChevronRight,
  BarChart3,
  Layers,
  AlertTriangle,
  Award,
  HeartPulse,
  Shield,
  CheckCircle2,
  FileCheck2,
  FileWarning,
  GraduationCap,
  UserX,
  Percent,
  RefreshCw,
  Loader2,
  AlertCircle,
} from "lucide-react";
import { apiClient } from "@/lib/api-client";
import { toast } from "sonner";

interface DashboardKpiData {
  overview: {
    totalStudents: number;
    totalFaculty: number;
    totalCourses: number;
    totalSubjects: number;
    activeAcademicSession: string;
    overallAttendancePercentage: number;
    defaultersCount: number;
    presentTodayCount: number;
    absentTodayCount: number;
    presentPercentage: string;
    absentPercentage: string;
  };
  statutoryEngine: {
    conductedHours: number;
    theoryHours: number;
    practicalHours: number;
    condonedHours: number;
    medicalHours: number;
    curriculumHoursDelivered: number;
    curriculumHoursTotal: number;
    curriculumProgressPct: string;
  };
  monthlyTrends: Array<{
    month: string;
    theoryHours: number;
    practicalHours: number;
  }>;
  subjectStatistics: Array<{
    code: string;
    name: string;
    conductedHours: number;
    plannedHours: number;
    attendanceRate: string;
    theoryHours: number;
    practicalHours: number;
  }>;
  complianceTiers: {
    totalEnrolled: number;
    evaluatedCount: number;
    compliantCount: number;
    warningCount: number;
    criticalCount: number;
    shortageCount: number;
    compliantPct: number;
    warningPct: number;
    criticalPct: number;
    shortagePct: number;
  };
  todaySessions: Array<{
    id: string;
    sessionId: string;
    subject: string;
    faculty: string;
    batchRoom: string;
    timeSlot: string;
    status: string;
    statusColor: string;
  }>;
  defaultersList: Array<{
    id: string;
    rollNo: string;
    name: string;
    semester: string;
    hours: string;
    percentage: string;
    status: string;
    statusColor: string;
  }>;
  operationsTimeline: Array<{
    title: string;
    subtitle: string;
    time: string;
    iconType?: string;
  }>;
  upcomingEvents: Array<{
    day: string;
    month: string;
    title: string;
    detail: string;
  }>;
  policyThresholds?: {
    minimumPercentage: number;
    warningPercentage: number;
    criticalPercentage: number;
  };
}

export default function SuperAdminDashboardPage() {
  const [data, setData] = useState<DashboardKpiData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isError, setIsError] = useState(false);

  // Fetch real database metrics from backend
  const fetchDashboardStats = useCallback(async (isManualRefresh = false) => {
    try {
      if (isManualRefresh) setIsRefreshing(true);
      else setIsLoading(true);
      setIsError(false);

      const res = await apiClient.get<{ success: boolean; data: DashboardKpiData }>("/dashboard/kpi");
      if (res.data?.success && res.data?.data) {
        setData(res.data.data);
        if (isManualRefresh) {
          toast.success("Dashboard metrics updated live from database!");
        }
      }
    } catch (err: unknown) {
      console.error("Failed to load dashboard KPIs:", err);
      setIsError(true);
      toast.error("Failed to fetch live database stats. Please check backend connection.");
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  }, []);

  useEffect(() => {
    fetchDashboardStats();
  }, [fetchDashboardStats]);

  // Dynamic date formatting
  const todayDate = new Date();
  const dayName = todayDate.toLocaleDateString("en-US", { weekday: "long" });
  const formattedDate = todayDate.toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });

  // 8 Quick Actions
  const quickActions = [
    {
      label: "Mark Attendance",
      icon: CalendarCheck,
      color: "bg-[#EFF6FF] text-[#2563EB] hover:bg-blue-100/80 border-blue-100",
      href: "/admin/sessions/generator",
    },
    {
      label: "View Defaulters",
      icon: AlertTriangle,
      color: "bg-[#FFF1F2] text-[#E11D48] hover:bg-rose-100/80 border-rose-100",
      href: "/admin/defaulters",
    },
    {
      label: "Generate APR",
      icon: Award,
      color: "bg-[#FEFCE8] text-[#CA8A04] hover:bg-yellow-100/80 border-yellow-100",
      href: "/admin/apr",
    },
    {
      label: "View Reports",
      icon: FileSpreadsheet,
      color: "bg-[#ECFDF5] text-[#059669] hover:bg-emerald-100/80 border-emerald-100",
      href: "/admin/reports/monthly-matrix",
    },
    {
      label: "Master Timetable",
      icon: Clock,
      color: "bg-[#FAF5FF] text-[#9333EA] hover:bg-purple-100/80 border-purple-100",
      href: "/admin/timetable",
    },
    {
      label: "Medical & Condonation",
      icon: HeartPulse,
      color: "bg-[#ECFEFF] text-[#0891B2] hover:bg-cyan-100/80 border-cyan-100",
      href: "/admin/adjustments/medical",
    },
    {
      label: "Attendance Rules",
      icon: Settings,
      color: "bg-[#FFFBEB] text-[#D97706] hover:bg-amber-100/80 border-amber-100",
      href: "/admin/policies",
    },
    {
      label: "Audit Logs",
      icon: Shield,
      color: "bg-[#EEF2FF] text-[#4F46E5] hover:bg-indigo-100/80 border-indigo-100",
      href: "/admin/audit-logs",
    },
  ];

  // Loading skeleton state
  if (isLoading && !data) {
    return (
      <div className="space-y-6 animate-pulse">
        <div className="h-32 bg-slate-200 rounded-2xl w-full" />
        <div className="h-14 bg-slate-200 rounded-xl w-full" />
        <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-3.5">
          {Array.from({ length: 7 }).map((_, i) => (
            <div key={i} className="h-28 bg-slate-200 rounded-xl" />
          ))}
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="h-72 bg-slate-200 rounded-xl" />
          <div className="h-72 bg-slate-200 rounded-xl" />
          <div className="h-72 bg-slate-200 rounded-xl" />
        </div>
        <div className="flex items-center justify-center p-8 text-slate-500 gap-2">
          <Loader2 className="w-5 h-5 animate-spin text-blue-600" />
          <span className="text-sm font-semibold">Loading live statistics from database...</span>
        </div>
      </div>
    );
  }

  // Error state
  if (isError && !data) {
    return (
      <div className="p-8 rounded-2xl bg-white border border-rose-200 shadow-sm text-center max-w-lg mx-auto my-12 space-y-4">
        <div className="w-12 h-12 bg-rose-50 text-rose-600 rounded-full flex items-center justify-center mx-auto">
          <AlertCircle className="w-6 h-6" />
        </div>
        <h2 className="text-lg font-bold text-slate-900">Database Connection Error</h2>
        <p className="text-xs text-slate-500">
          Unable to query live operational statistics from MySQL database. Please make sure the backend server is running on port 5000.
        </p>
        <button
          onClick={() => fetchDashboardStats(true)}
          className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold text-xs rounded-lg transition-colors cursor-pointer inline-flex items-center gap-2"
        >
          <RefreshCw className="w-3.5 h-3.5" />
          <span>Retry Loading</span>
        </button>
      </div>
    );
  }

  const overview = data?.overview;
  const engine = data?.statutoryEngine;
  const tiers = data?.complianceTiers;
  const trends = data?.monthlyTrends || [];
  const subjects = data?.subjectStatistics || [];
  const sessions = data?.todaySessions || [];
  const defaulters = data?.defaultersList || [];
  const timeline = data?.operationsTimeline || [];
  const events = data?.upcomingEvents || [];

  // Determine max value for monthly chart scaling
  const maxMonthlyHour = Math.max(
    ...trends.flatMap((t) => [t.theoryHours, t.practicalHours]),
    10
  );

  return (
    <div className="space-y-6">
      {/* ============================================================ */}
      {/* 1. HERO GREETING BANNER WITH CAMPUS BACKDROP                */}
      {/* ============================================================ */}
      <div className="relative overflow-hidden rounded-2xl bg-white border border-slate-200/90 shadow-2xs p-6 sm:p-7 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-6 min-h-[140px]">
        {/* Campus architectural photo on right with seamless gradient mask */}
        <div
          className="absolute right-0 top-0 bottom-0 w-2/3 sm:w-1/2 bg-cover bg-center pointer-events-none opacity-90"
          style={{
            backgroundImage: `url('/images/ihm_campus_bg.jpg')`,
            maskImage: "linear-gradient(to right, transparent 0%, black 50%)",
            WebkitMaskImage: "linear-gradient(to right, transparent 0%, black 50%)",
          }}
        />

        {/* Left greeting typography */}
        <div className="relative z-10 max-w-xl">
          <div className="flex items-center gap-2">
            <h1 className="font-heading font-bold text-2xl sm:text-3xl text-[#0B1F33] tracking-tight">
              Good Morning, Admin!
            </h1>
            <span className="text-2xl">👋</span>
          </div>
          <p className="text-xs sm:text-sm text-[#536273] mt-1 font-normal">
            Academic Operations Console • Live records for session{" "}
            <span className="font-semibold text-slate-800 font-mono">
              {overview?.activeAcademicSession || "Current"}
            </span>{" "}
            from MySQL database.
          </p>
        </div>

        {/* Date Pill & Refresh Control */}
        <div className="relative z-10 flex items-center gap-2">
          <button
            onClick={() => fetchDashboardStats(true)}
            disabled={isRefreshing}
            className="p-2.5 rounded-xl bg-white/95 backdrop-blur-md border border-slate-200/90 text-slate-600 hover:text-blue-600 hover:bg-slate-50 transition-colors cursor-pointer shadow-xs"
            title="Refresh statistics live from database"
          >
            <RefreshCw className={`w-4 h-4 ${isRefreshing ? "animate-spin text-blue-600" : ""}`} />
          </button>

          <div className="flex items-center gap-3 px-4 py-2.5 rounded-xl bg-white/95 backdrop-blur-md border border-slate-200/90 shadow-xs">
            <div className="w-9 h-9 rounded-lg bg-blue-50 border border-blue-100 text-blue-600 flex items-center justify-center shrink-0">
              <Calendar className="w-4 h-4" />
            </div>
            <div className="leading-tight text-left">
              <span className="text-[11px] text-slate-400 font-medium block">
                {dayName}
              </span>
              <span className="text-xs font-bold text-slate-800 font-mono block">
                {formattedDate}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 2. STATUTORY ATTENDANCE CALCULATION ENGINE BANNER           */}
      {/* ============================================================ */}
      <div className="bg-white border border-[#C8A45D]/40 rounded-xl p-3.5 sm:p-4 shadow-2xs flex flex-col md:flex-row items-start md:items-center justify-between gap-4 bg-gradient-to-r from-amber-50/25 via-white to-blue-50/20">
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 rounded-lg bg-[#0B1F33] text-[#C8A45D] flex items-center justify-center shrink-0 shadow-xs border border-[#C8A45D]/30">
            <Award className="w-4 h-4" />
          </div>
          <div>
            <div className="flex items-center gap-2 flex-wrap">
              <span className="text-xs font-bold text-[#0B1F33]">
                Statutory Attendance Calculation Engine
              </span>
              <span className="text-[10px] px-2 py-0.5 rounded-full bg-[#C8A45D]/20 text-[#7a5e1e] font-extrabold border border-[#C8A45D]/30">
                Live Database Aggregation
              </span>
            </div>
            <p className="text-[11px] text-slate-500 font-mono mt-0.5">
              Attendance % ={" "}
              <span className="font-semibold text-slate-800">
                (Present Hours + Condonation Hours + Approved Medical Hours) ÷ Conducted Hours × 100
              </span>
            </p>
          </div>
        </div>

        {/* Live Calculation Metric Counter from Database */}
        <div className="flex items-center gap-3 sm:gap-4 text-xs font-mono shrink-0 overflow-x-auto w-full md:w-auto pb-1 md:pb-0">
          <div className="text-center sm:text-left">
            <span className="text-slate-400 text-[10px] block font-sans">Conducted</span>
            <span className="font-bold text-[#0B1F33]">{engine?.conductedHours ?? 0}h</span>
          </div>
          <div className="w-px h-6 bg-slate-200" />
          <div className="text-center sm:text-left">
            <span className="text-slate-400 text-[10px] block font-sans">Theory</span>
            <span className="font-bold text-[#C8A45D]">{engine?.theoryHours ?? 0}h</span>
          </div>
          <div className="w-px h-6 bg-slate-200" />
          <div className="text-center sm:text-left">
            <span className="text-slate-400 text-[10px] block font-sans">Practical</span>
            <span className="font-bold text-[#0B1F33]">{engine?.practicalHours ?? 0}h</span>
          </div>
          <div className="w-px h-6 bg-slate-200" />
          <div className="text-center sm:text-left">
            <span className="text-slate-400 text-[10px] block font-sans">Condoned</span>
            <span className="font-bold text-amber-600">{engine?.condonedHours ?? 0}h</span>
          </div>
          <div className="w-px h-6 bg-slate-200" />
          <div className="text-center sm:text-left">
            <span className="text-slate-400 text-[10px] block font-sans">Medical</span>
            <span className="font-bold text-teal-600">{engine?.medicalHours ?? 0}h</span>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 3. STATUTORY INSTITUTIONAL KPI METRICS                      */}
      {/* ============================================================ */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-7 gap-3.5">
        {/* Metric 1: Total Students */}
        <Link
          href="/admin/people/students/records"
          className="p-4 rounded-xl bg-white border border-slate-200/90 shadow-2xs hover:shadow-xs hover:border-blue-300 transition-all flex flex-col justify-between group cursor-pointer"
        >
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-blue-50 border border-blue-100 text-blue-600 flex items-center justify-center shrink-0 group-hover:scale-105 transition-transform">
              <GraduationCap className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded-full border border-blue-200/60">
              Active
            </span>
          </div>
          <div>
            <div className="text-xl sm:text-2xl font-black text-[#0B1F33] font-mono tracking-tight leading-tight">
              {overview?.totalStudents ?? 0}
            </div>
            <div className="text-xs font-bold text-slate-700 mt-0.5">Total Students</div>
            <div className="text-[10px] text-slate-400 font-medium truncate mt-0.5">
              Enrolled in DB
            </div>
          </div>
        </Link>

        {/* Metric 2: Total Faculty */}
        <Link
          href="/admin/people/faculty"
          className="p-4 rounded-xl bg-white border border-slate-200/90 shadow-2xs hover:shadow-xs hover:border-indigo-300 transition-all flex flex-col justify-between group cursor-pointer"
        >
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-indigo-50 border border-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 group-hover:scale-105 transition-transform">
              <UserCheck className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-indigo-600 bg-indigo-50 px-1.5 py-0.5 rounded-full border border-indigo-200/60">
              Faculty
            </span>
          </div>
          <div>
            <div className="text-xl sm:text-2xl font-black text-[#0B1F33] font-mono tracking-tight leading-tight">
              {overview?.totalFaculty ?? 0}
            </div>
            <div className="text-xs font-bold text-slate-700 mt-0.5">Total Faculty</div>
            <div className="text-[10px] text-slate-400 font-medium truncate mt-0.5">
              Active Instructors
            </div>
          </div>
        </Link>

        {/* Metric 3: Total Courses */}
        <Link
          href="/admin/academic/courses"
          className="p-4 rounded-xl bg-white border border-slate-200/90 shadow-2xs hover:shadow-xs hover:border-purple-300 transition-all flex flex-col justify-between group cursor-pointer"
        >
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-purple-50 border border-purple-100 text-purple-600 flex items-center justify-center shrink-0 group-hover:scale-105 transition-transform">
              <BookOpen className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-purple-600 bg-purple-50 px-1.5 py-0.5 rounded-full border border-purple-200/60">
              Programs
            </span>
          </div>
          <div>
            <div className="text-xl sm:text-2xl font-black text-[#0B1F33] font-mono tracking-tight leading-tight">
              {overview?.totalCourses ?? 0}
            </div>
            <div className="text-xs font-bold text-slate-700 mt-0.5">Total Courses</div>
            <div className="text-[10px] text-slate-400 font-medium truncate mt-0.5">
              NCHMCT Approved
            </div>
          </div>
        </Link>

        {/* Metric 4: Present Records */}
        <Link
          href="/admin/sessions/generator"
          className="p-4 rounded-xl bg-white border border-slate-200/90 shadow-2xs hover:shadow-xs hover:border-emerald-300 transition-all flex flex-col justify-between group cursor-pointer"
        >
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-emerald-50 border border-emerald-100 text-emerald-600 flex items-center justify-center shrink-0 group-hover:scale-105 transition-transform">
              <CheckCircle2 className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-emerald-700 bg-emerald-50 px-1.5 py-0.5 rounded-full border border-emerald-200/60">
              {overview?.presentPercentage || "0%"}
            </span>
          </div>
          <div>
            <div className="text-xl sm:text-2xl font-black text-emerald-700 font-mono tracking-tight leading-tight">
              {overview?.presentTodayCount ?? 0}
            </div>
            <div className="text-xs font-bold text-slate-700 mt-0.5">Present Records</div>
            <div className="text-[10px] text-emerald-600 font-medium truncate mt-0.5">
              Marked P / C
            </div>
          </div>
        </Link>

        {/* Metric 5: Absent Records */}
        <Link
          href="/admin/sessions/generator"
          className="p-4 rounded-xl bg-white border border-slate-200/90 shadow-2xs hover:shadow-xs hover:border-rose-300 transition-all flex flex-col justify-between group cursor-pointer"
        >
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-rose-50 border border-rose-100 text-rose-600 flex items-center justify-center shrink-0 group-hover:scale-105 transition-transform">
              <UserX className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-rose-700 bg-rose-50 px-1.5 py-0.5 rounded-full border border-rose-200/60">
              {overview?.absentPercentage || "0%"}
            </span>
          </div>
          <div>
            <div className="text-xl sm:text-2xl font-black text-rose-600 font-mono tracking-tight leading-tight">
              {overview?.absentTodayCount ?? 0}
            </div>
            <div className="text-xs font-bold text-slate-700 mt-0.5">Absent Records</div>
            <div className="text-[10px] text-rose-500 font-medium truncate mt-0.5">
              Marked Absent (A)
            </div>
          </div>
        </Link>

        {/* Metric 6: Overall Attendance */}
        <Link
          href="/admin/reports/percentage"
          className="p-4 rounded-xl bg-white border border-[#C8A45D]/40 shadow-2xs hover:shadow-xs hover:border-[#C8A45D] transition-all flex flex-col justify-between group bg-gradient-to-b from-amber-50/20 to-white cursor-pointer"
        >
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-[#0B1F33] text-[#C8A45D] flex items-center justify-center shrink-0 group-hover:scale-105 transition-transform shadow-xs">
              <Percent className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-[#7a5e1e] bg-amber-100/60 px-1.5 py-0.5 rounded-full border border-amber-300/60">
              Statutory
            </span>
          </div>
          <div>
            <div className="text-xl sm:text-2xl font-black text-[#0B1F33] font-mono tracking-tight leading-tight">
              {overview?.overallAttendancePercentage ?? 0}%
            </div>
            <div className="text-xs font-bold text-slate-800 mt-0.5">Overall Attendance</div>
            <div className="text-[10px] text-amber-700 font-medium truncate mt-0.5">
              Active Cohort Avg
            </div>
          </div>
        </Link>

        {/* Metric 7: Attendance Defaulters */}
        <Link
          href="/admin/defaulters"
          className="p-4 rounded-xl bg-white border border-rose-200/80 shadow-2xs hover:shadow-xs hover:border-red-400 transition-all flex flex-col justify-between group bg-gradient-to-b from-rose-50/20 to-white cursor-pointer"
        >
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-red-100 text-red-600 flex items-center justify-center shrink-0 group-hover:scale-105 transition-transform">
              <AlertTriangle className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-red-700 bg-red-50 px-1.5 py-0.5 rounded-full border border-red-200">
              &lt; 75%
            </span>
          </div>
          <div>
            <div className="text-xl sm:text-2xl font-black text-red-600 font-mono tracking-tight leading-tight">
              {overview?.defaultersCount ?? 0}
            </div>
            <div className="text-xs font-bold text-slate-800 mt-0.5">Defaulters List</div>
            <div className="text-[10px] text-red-500 font-medium truncate mt-0.5">
              Subject Level Shortage
            </div>
          </div>
        </Link>
      </div>

      {/* ============================================================ */}
      {/* 4. MIDDLE ANALYTICS SECTION: 3 COLUMNS                      */}
      {/* ============================================================ */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Card 1: Monthly Attendance & Contact Hours Statistics (Bar Chart) */}
        <div className="p-5 sm:p-6 rounded-xl bg-white border border-slate-200/90 shadow-2xs flex flex-col justify-between">
          <div>
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-blue-600" />
                <h3 className="text-xs sm:text-sm font-bold text-slate-900">
                  Monthly Contact Hours Trend
                </h3>
              </div>
              <span className="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 text-slate-700 font-semibold font-mono">
                {overview?.activeAcademicSession || "Current"}
              </span>
            </div>

            {/* Custom SVG Bar Chart with Grid */}
            <div className="h-56 w-full pt-2 flex flex-col justify-end">
              <div className="relative flex-1 flex">
                {/* Y-Axis markers */}
                <div className="w-8 flex flex-col justify-between text-[10px] text-slate-400 font-mono pr-1.5 pb-6 text-right select-none">
                  <span>{Math.round(maxMonthlyHour)}h</span>
                  <span>{Math.round(maxMonthlyHour * 0.75)}h</span>
                  <span>{Math.round(maxMonthlyHour * 0.5)}h</span>
                  <span>{Math.round(maxMonthlyHour * 0.25)}h</span>
                  <span>0h</span>
                </div>

                {/* Bars Area with horizontal dashed lines */}
                <div className="flex-1 relative flex flex-col justify-between pb-6">
                  {/* Subtle Grid Lines */}
                  <div className="absolute inset-x-0 top-0 border-b border-dashed border-slate-100" />
                  <div className="absolute inset-x-0 top-1/4 border-b border-dashed border-slate-100" />
                  <div className="absolute inset-x-0 top-2/4 border-b border-dashed border-slate-100" />
                  <div className="absolute inset-x-0 top-3/4 border-b border-dashed border-slate-100" />
                  <div className="absolute inset-x-0 bottom-6 border-b border-slate-200" />

                  {/* Bars row */}
                  <div className="relative z-10 h-full flex items-end justify-around px-2">
                    {trends.map((d) => {
                      const theoryHeight = maxMonthlyHour > 0 ? (d.theoryHours / maxMonthlyHour) * 135 : 0;
                      const practicalHeight = maxMonthlyHour > 0 ? (d.practicalHours / maxMonthlyHour) * 135 : 0;

                      return (
                        <div key={d.month} className="flex flex-col items-center flex-1">
                          {/* Values above bars */}
                          <div className="flex gap-1 mb-1 text-[8px] sm:text-[9px] font-mono text-slate-500 font-medium">
                            <span className="text-[#C8A45D]">{d.theoryHours}</span>
                            <span>{d.practicalHours}</span>
                          </div>

                          {/* Bars Pair */}
                          <div className="flex items-end gap-1">
                            {/* Theory Hours (Gold) */}
                            <div
                              style={{ height: `${Math.max(theoryHeight, 4)}px` }}
                              className="w-2.5 sm:w-3.5 rounded-t bg-[#C8A45D] hover:opacity-90 transition-all shadow-2xs"
                              title={`Theory: ${d.theoryHours}h`}
                            />
                            {/* Practical Lab Hours (Navy) */}
                            <div
                              style={{ height: `${Math.max(practicalHeight, 4)}px` }}
                              className="w-2.5 sm:w-3.5 rounded-t bg-[#0B1F33] hover:opacity-90 transition-all shadow-2xs"
                              title={`Practical: ${d.practicalHours}h`}
                            />
                          </div>

                          {/* Month label below baseline */}
                          <span className="text-[10px] text-slate-500 font-medium mt-1.5 absolute -bottom-5">
                            {d.month}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>

              {/* Chart Legend */}
              <div className="flex items-center justify-center gap-5 text-[11px] text-slate-600 mt-5 pt-2 border-t border-slate-100">
                <div className="flex items-center gap-1.5">
                  <div className="w-2.5 h-2.5 rounded-full bg-[#C8A45D]" />
                  <span>Theory Contact</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <div className="w-2.5 h-2.5 rounded-full bg-[#0B1F33]" />
                  <span>Kitchen/Lab Practical</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Card 2: Subject Statistics & Teaching Progress */}
        <div className="p-5 sm:p-6 rounded-xl bg-white border border-slate-200/90 shadow-2xs flex flex-col justify-between">
          <div>
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <BookOpen className="w-4 h-4 text-emerald-600" />
                <h3 className="text-xs sm:text-sm font-bold text-slate-900">
                  Subject Statistics & Teaching Progress
                </h3>
              </div>
              <Link
                href="/admin/academic/subjects"
                className="text-[11px] font-semibold text-[#C8A45D] hover:underline"
              >
                All Subjects →
              </Link>
            </div>

            {/* Teaching Hours Progress Bar */}
            <div className="p-3 bg-slate-50 rounded-lg border border-slate-100 mb-3">
              <div className="flex items-center justify-between text-xs mb-1.5">
                <span className="font-bold text-slate-800">Curriculum Hours Delivered</span>
                <span className="font-mono font-bold text-[#0B1F33]">
                  {engine?.curriculumHoursDelivered ?? 0} / {engine?.curriculumHoursTotal ?? 0} hrs ({engine?.curriculumProgressPct ?? "0"}%)
                </span>
              </div>
              <div className="w-full bg-slate-200 rounded-full h-2 overflow-hidden flex">
                <div
                  className="bg-[#0B1F33] h-2 transition-all"
                  style={{ width: `${Math.min(Number(engine?.curriculumProgressPct || 0), 100)}%` }}
                />
              </div>
              <div className="flex items-center justify-between text-[10px] text-slate-400 mt-1 font-mono">
                <span>Completed: {engine?.curriculumHoursDelivered ?? 0}h</span>
                <span>
                  Remaining: {Math.max((engine?.curriculumHoursTotal ?? 0) - (engine?.curriculumHoursDelivered ?? 0), 0)}h
                </span>
              </div>
            </div>

            {/* Subject Statistics List */}
            <div className="space-y-2 text-xs">
              {subjects.length === 0 ? (
                <div className="p-4 text-center text-slate-400 text-xs">
                  No registered subjects found in active database.
                </div>
              ) : (
                subjects.map((sub) => (
                  <div
                    key={sub.code}
                    className="p-2 rounded-lg border border-slate-100 hover:border-slate-200 bg-white transition-all flex items-center justify-between gap-2"
                  >
                    <div className="min-w-0">
                      <div className="flex items-center gap-1.5">
                        <span className="px-1.5 py-0.2 rounded text-[9px] font-bold font-mono bg-blue-50 text-blue-700 border border-blue-200">
                          {sub.code}
                        </span>
                        <span className="font-bold text-slate-800 truncate text-[11px]">
                          {sub.name}
                        </span>
                      </div>
                      <div className="text-[10px] text-slate-400 font-mono mt-0.5">
                        Theory: {sub.theoryHours}h • Practical: {sub.practicalHours}h ({sub.conductedHours}/{sub.plannedHours}h)
                      </div>
                    </div>

                    <div className="text-right shrink-0">
                      <span className="font-mono font-extrabold text-emerald-600 block text-xs">
                        {sub.attendanceRate}
                      </span>
                      <span className="text-[9px] text-slate-400 block font-sans">
                        Avg Attd
                      </span>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>

        {/* Card 3: Attendance Rules & Defaulter Tiers (Donut Chart) */}
        <div className="p-5 sm:p-6 rounded-xl bg-white border border-slate-200/90 shadow-2xs flex flex-col justify-between">
          <div>
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <Layers className="w-4 h-4 text-purple-600" />
                <h3 className="text-xs sm:text-sm font-bold text-slate-900">
                  Compliance & Defaulter Tiers
                </h3>
              </div>
              <span className="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 text-slate-700 font-semibold font-mono">
                Statutory Tiers
              </span>
            </div>

            {/* Side-by-side Donut & Legend */}
            <div className="flex flex-col sm:flex-row items-center justify-between gap-4 py-2">
              <div className="relative w-36 h-36 shrink-0 flex items-center justify-center">
                <svg className="w-full h-full transform -rotate-90" viewBox="0 0 36 36">
                  <circle
                    cx="18"
                    cy="18"
                    r="15.5"
                    fill="none"
                    stroke="#F1F5F9"
                    strokeWidth="4"
                  />
                  {/* Compliant Tier >= 75% */}
                  <circle
                    cx="18"
                    cy="18"
                    r="15.5"
                    fill="none"
                    stroke="#10B981"
                    strokeWidth="4.5"
                    strokeDasharray={`${tiers?.compliantPct ?? 0}, 100`}
                    strokeDashoffset="0"
                  />
                  {/* Warning Tier 70-74% */}
                  <circle
                    cx="18"
                    cy="18"
                    r="15.5"
                    fill="none"
                    stroke="#FBBF24"
                    strokeWidth="4.5"
                    strokeDasharray={`${tiers?.warningPct ?? 0}, 100`}
                    strokeDashoffset={`-${tiers?.compliantPct ?? 0}`}
                  />
                  {/* Critical Tier 65-69% */}
                  <circle
                    cx="18"
                    cy="18"
                    r="15.5"
                    fill="none"
                    stroke="#F97316"
                    strokeWidth="4.5"
                    strokeDasharray={`${tiers?.criticalPct ?? 0}, 100`}
                    strokeDashoffset={`-${(tiers?.compliantPct ?? 0) + (tiers?.warningPct ?? 0)}`}
                  />
                  {/* Severe Shortage < 65% */}
                  <circle
                    cx="18"
                    cy="18"
                    r="15.5"
                    fill="none"
                    stroke="#EF4444"
                    strokeWidth="4.5"
                    strokeDasharray={`${tiers?.shortagePct ?? 0}, 100`}
                    strokeDashoffset={`-${(tiers?.compliantPct ?? 0) + (tiers?.warningPct ?? 0) + (tiers?.criticalPct ?? 0)}`}
                  />
                </svg>

                <div className="absolute text-center">
                  <span className="text-base font-extrabold text-[#0B1F33] block leading-tight">
                    {tiers?.totalEnrolled ?? 0}
                  </span>
                  <span className="text-[10px] text-slate-400 font-medium">
                    Enrolled
                  </span>
                </div>
              </div>

              {/* Status Breakdown Legend */}
              <div className="space-y-1.5 text-xs text-slate-600 flex-1 w-full sm:w-auto">
                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2 truncate">
                    <div className="w-2.5 h-2.5 rounded-full bg-[#10B981] shrink-0" />
                    <span className="truncate">Compliant (&ge; 75%)</span>
                  </div>
                  <span className="font-bold text-slate-900 font-mono">
                    {tiers?.compliantCount ?? 0}
                  </span>
                </div>
                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2 truncate">
                    <div className="w-2.5 h-2.5 rounded-full bg-[#FBBF24] shrink-0" />
                    <span className="truncate">Warning (70–74%)</span>
                  </div>
                  <span className="font-bold text-slate-900 font-mono">
                    {tiers?.warningCount ?? 0}
                  </span>
                </div>
                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2 truncate">
                    <div className="w-2.5 h-2.5 rounded-full bg-[#F97316] shrink-0" />
                    <span className="truncate">Critical (65–69%)</span>
                  </div>
                  <span className="font-bold text-slate-900 font-mono">
                    {tiers?.criticalCount ?? 0}
                  </span>
                </div>
                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2 truncate">
                    <div className="w-2.5 h-2.5 rounded-full bg-[#EF4444] shrink-0" />
                    <span className="truncate">Shortage (&lt; 65%)</span>
                  </div>
                  <span className="font-bold text-slate-900 font-mono">
                    {tiers?.shortageCount ?? 0}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 4. DATA TABLES SECTION (2 COLUMNS)                          */}
      {/* ============================================================ */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Table 1: Real Database Attendance Sessions */}
        <div className="p-5 sm:p-6 rounded-xl bg-white border border-slate-200/90 shadow-2xs">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <CalendarCheck className="w-4 h-4 text-emerald-600" />
              <h3 className="text-xs sm:text-sm font-bold text-slate-900">
                Class Attendance Sessions (From DB)
              </h3>
            </div>
            <Link
              href="/admin/sessions/generator"
              className="text-xs font-semibold text-[#C8A45D] hover:underline flex items-center gap-1"
            >
              <span>View Generator</span>
              <ArrowRight className="w-3.5 h-3.5" />
            </Link>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs">
              <thead className="bg-slate-50 text-slate-500 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
                <tr>
                  <th className="py-2.5 px-3">#</th>
                  <th className="py-2.5 px-3">Subject</th>
                  <th className="py-2.5 px-3">Faculty</th>
                  <th className="py-2.5 px-3">Batch & Venue</th>
                  <th className="py-2.5 px-3">Status</th>
                  <th className="py-2.5 px-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {sessions.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="py-6 text-center text-slate-400">
                      No attendance sessions recorded in database.
                    </td>
                  </tr>
                ) : (
                  sessions.map((session) => (
                    <tr key={session.id} className="hover:bg-slate-50/70 transition-colors">
                      <td className="py-3 px-3 font-mono text-slate-400">{session.id}</td>
                      <td className="py-3 px-3 font-semibold text-slate-900">
                        {session.subject}
                      </td>
                      <td className="py-3 px-3 text-slate-600">{session.faculty}</td>
                      <td className="py-3 px-3 text-slate-400 font-mono text-[11px]">
                        {session.batchRoom}
                      </td>
                      <td className="py-3 px-3">
                        <span
                          className={`inline-block px-2.5 py-0.5 rounded-full text-[10px] font-bold border ${session.statusColor}`}
                        >
                          {session.status}
                        </span>
                      </td>
                      <td className="py-3 px-3 text-right">
                        <Link
                          href="/admin/sessions/generator"
                          className="p-1 rounded text-slate-400 hover:text-slate-800 hover:bg-slate-100 transition-colors inline-block"
                          title="View session"
                        >
                          <Eye className="w-3.5 h-3.5" />
                        </Link>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Table 2: Defaulter Students in Shortage Tier (< 75%) */}
        <div className="p-5 sm:p-6 rounded-xl bg-white border border-slate-200/90 shadow-2xs">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <AlertTriangle className="w-4 h-4 text-rose-600" />
              <h3 className="text-xs sm:text-sm font-bold text-slate-900">
                Defaulters in Shortage Tier (&lt; 75%)
              </h3>
            </div>
            <Link
              href="/admin/defaulters"
              className="text-xs font-semibold text-[#C8A45D] hover:underline flex items-center gap-1"
            >
              <span>Manage Defaulters</span>
              <ArrowRight className="w-3.5 h-3.5" />
            </Link>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs">
              <thead className="bg-slate-50 text-slate-500 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
                <tr>
                  <th className="py-2.5 px-3">#</th>
                  <th className="py-2.5 px-3">Roll No</th>
                  <th className="py-2.5 px-3">Name</th>
                  <th className="py-2.5 px-3">Attended / Total</th>
                  <th className="py-2.5 px-3">Attendance %</th>
                  <th className="py-2.5 px-3 text-right">Tier</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {defaulters.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="py-6 text-center text-slate-400">
                      No attendance defaulters below 75% in active database records.
                    </td>
                  </tr>
                ) : (
                  defaulters.map((st) => (
                    <tr key={st.id} className="hover:bg-slate-50/70 transition-colors">
                      <td className="py-3 px-3 font-mono text-slate-400">{st.id}</td>
                      <td className="py-3 px-3 font-mono text-slate-600 font-medium">{st.rollNo}</td>
                      <td className="py-3 px-3 font-semibold text-slate-900">
                        {st.name}
                      </td>
                      <td className="py-3 px-3 text-slate-400 font-mono text-[11px]">
                        {st.hours}
                      </td>
                      <td className="py-3 px-3 font-mono font-bold text-rose-600">
                        {st.percentage}
                      </td>
                      <td className="py-3 px-3 text-right">
                        <span className={`inline-block px-2.5 py-0.5 rounded-full text-[10px] font-bold border ${st.statusColor}`}>
                          {st.status}
                        </span>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 5. BOTTOM SECTION: ACTIVITIES, EVENTS & QUICK ACTIONS        */}
      {/* ============================================================ */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Widget 1: Real DB Operations Timeline (From audit_logs) */}
        <div className="p-5 sm:p-6 rounded-xl bg-white border border-slate-200/90 shadow-2xs flex flex-col justify-between">
          <div>
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <Clock className="w-4 h-4 text-blue-600" />
                <h3 className="text-xs sm:text-sm font-bold text-slate-900">
                  Operations Timeline (Audit Trail)
                </h3>
              </div>
              <Link href="/admin/audit-logs" className="text-xs font-semibold text-[#C8A45D] hover:underline">
                View All →
              </Link>
            </div>

            <div className="relative pl-6 space-y-4 pt-1">
              <div className="absolute left-[11px] top-3 bottom-3 w-0.5 bg-slate-200" />

              {timeline.length === 0 ? (
                <div className="text-xs text-slate-400 py-3">No activity logs recorded yet.</div>
              ) : (
                timeline.map((act, i) => (
                  <div key={i} className="relative flex items-start justify-between gap-3">
                    <div className="absolute -left-6 w-5 h-5 rounded-full flex items-center justify-center text-white bg-blue-500 shadow-2xs ring-4 ring-white">
                      <Clock className="w-2.5 h-2.5" />
                    </div>

                    <div className="min-w-0 flex-1">
                      <h4 className="text-xs font-bold text-slate-800 leading-tight">
                        {act.title}
                      </h4>
                      <p className="text-[11px] text-slate-500 truncate mt-0.5">
                        {act.subtitle}
                      </p>
                    </div>

                    <span className="text-[10px] text-slate-400 font-mono shrink-0">
                      {act.time}
                    </span>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>

        {/* Widget 2: Real DB Upcoming Events (From holidays & notices) */}
        <div className="p-5 sm:p-6 rounded-xl bg-white border border-slate-200/90 shadow-2xs flex flex-col justify-between">
          <div>
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4 text-rose-600" />
                <h3 className="text-xs sm:text-sm font-bold text-slate-900">
                  Academic Events &amp; Notices
                </h3>
              </div>
              <Link href="/admin/holidays" className="text-xs font-semibold text-[#C8A45D] hover:underline">
                View Calendar →
              </Link>
            </div>

            <div className="space-y-3">
              {events.length === 0 ? (
                <div className="text-xs text-slate-400 py-3">No upcoming events or notices.</div>
              ) : (
                events.map((ev, i) => (
                  <div
                    key={i}
                    className="flex items-center justify-between p-2 rounded-lg hover:bg-slate-50 transition-colors"
                  >
                    <div className="flex items-center gap-3 min-w-0">
                      <div className="w-10 h-10 rounded-lg bg-red-50 border border-red-100 flex flex-col items-center justify-center shrink-0">
                        <span className="text-xs font-black text-red-600 leading-none">
                          {ev.day}
                        </span>
                        <span className="text-[8px] font-bold text-red-400 uppercase leading-none mt-0.5">
                          {ev.month}
                        </span>
                      </div>

                      <div className="truncate">
                        <h4 className="text-xs font-bold text-slate-800 leading-tight truncate">
                          {ev.title}
                        </h4>
                        <p className="text-[10px] text-slate-400 mt-0.5 truncate">
                          {ev.detail}
                        </p>
                      </div>
                    </div>

                    <ChevronRight className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                  </div>
                ))
              )}
            </div>
          </div>
        </div>

        {/* Widget 3: 8 Quick Actions */}
        <div className="p-5 sm:p-6 rounded-xl bg-white border border-slate-200/90 shadow-2xs flex flex-col justify-between">
          <div>
            <div className="flex items-center gap-2 mb-4">
              <Settings className="w-4 h-4 text-amber-600" />
              <h3 className="text-xs sm:text-sm font-bold text-slate-900">
                Quick Actions
              </h3>
            </div>

            <div className="grid grid-cols-2 gap-2.5">
              {quickActions.map((qa) => {
                const Icon = qa.icon;
                return (
                  <Link
                    key={qa.label}
                    href={qa.href}
                    className={`p-3 rounded-lg border flex flex-col items-center text-center gap-1.5 transition-all shadow-2xs ${qa.color}`}
                  >
                    <Icon className="w-4 h-4" />
                    <span className="text-[11px] font-bold leading-tight">
                      {qa.label}
                    </span>
                  </Link>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
