"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  BarChart3,
  Download,
  Printer,
  FileSpreadsheet,
  Calendar,
  Filter,
  Search,
  ChevronRight,
  AlertTriangle,
  CheckCircle2,
  Users,
  BookOpen,
  UtensilsCrossed,
} from "lucide-react";
import { toast } from "sonner";

interface DefaulterRecord {
  rollNo: string;
  name: string;
  semester: number;
  batch: string;
  totalHeld: number;
  attended: number;
  percentage: number;
  status: "CRITICAL" | "CONDONATION_ELIGIBLE";
}

export default function DeptAdminReportsPage() {
  const [selectedReportType, setSelectedReportType] = useState<string>("defaulters");
  const [selectedSem, setSelectedSem] = useState<number | "ALL">("ALL");
  const [search, setSearch] = useState("");

  const defaulters: DefaulterRecord[] = [
    {
      rollNo: "2441112089",
      name: "Rahul Roychowdhury",
      semester: 5,
      batch: "Kitchen Batch A1",
      totalHeld: 142,
      attended: 96,
      percentage: 67.8,
      status: "CONDONATION_ELIGIBLE",
    },
    {
      rollNo: "2441112015",
      name: "Debashis Sen",
      semester: 3,
      batch: "Kitchen Batch Q1",
      totalHeld: 148,
      attended: 105,
      percentage: 71.2,
      status: "CONDONATION_ELIGIBLE",
    },
    {
      rollNo: "2441112048",
      name: "Vikramjit Chatterjee",
      semester: 3,
      batch: "Kitchen Batch Q2",
      totalHeld: 148,
      attended: 88,
      percentage: 59.4,
      status: "CRITICAL",
    },
    {
      rollNo: "2441112061",
      name: "Roshni Paul",
      semester: 1,
      batch: "Kitchen Batch K1",
      totalHeld: 130,
      attended: 94,
      percentage: 72.3,
      status: "CONDONATION_ELIGIBLE",
    },
    {
      rollNo: "2441112078",
      name: "Tanmay Ghosh",
      semester: 1,
      batch: "Kitchen Batch K2",
      totalHeld: 130,
      attended: 81,
      percentage: 62.3,
      status: "CRITICAL",
    },
  ];

  const filteredDefaulters = defaulters.filter((d) => {
    const matchesSem = selectedSem === "ALL" || d.semester === selectedSem;
    const matchesSearch =
      d.name.toLowerCase().includes(search.toLowerCase()) ||
      d.rollNo.includes(search);
    return matchesSem && matchesSearch;
  });

  const handleExport = (format: "CSV" | "PDF") => {
    toast.success(`Exporting ${selectedReportType.toUpperCase()} report as ${format}...`);
  };

  return (
    <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 text-xs font-semibold text-slate-500 mb-1">
            <Link href="/dept-admin/dashboard" className="hover:text-[#1769E8]">
              Dashboard
            </Link>
            <ChevronRight className="w-3.5 h-3.5" />
            <span className="text-[#071A4D] font-bold">Reports</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-black text-[#071A4D] tracking-tight">
            Department Attendance Analytics & Reports
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Defaulter rosters, kitchen practical compliance, daily registers, and NCHMCT eligibility records
          </p>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => handleExport("PDF")}
            className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 text-xs font-bold transition-all"
          >
            <Printer className="w-3.5 h-3.5" />
            <span>Download PDF</span>
          </button>
          <button
            onClick={() => handleExport("CSV")}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[#C8A45D] hover:bg-[#B38F48] text-slate-950 font-bold text-xs shadow-sm transition-all"
          >
            <Download className="w-4 h-4" />
            <span>Export CSV</span>
          </button>
        </div>
      </div>

      {/* KPI Stats Strip */}
      <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-xs">
          <div className="text-xs text-slate-500">Classes Conducted</div>
          <div className="text-2xl font-black text-[#071A4D] mt-1">420 Sessions</div>
          <div className="text-[10px] text-emerald-600 font-bold mt-1">98.2% on schedule</div>
        </div>

        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-xs">
          <div className="text-xs text-slate-500">Department Average</div>
          <div className="text-2xl font-black text-emerald-700 mt-1">81.4%</div>
          <div className="text-[10px] text-slate-400 mt-1">Mandate: &gt;= 75%</div>
        </div>

        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-xs">
          <div className="text-xs text-slate-500">Current Defaulters</div>
          <div className="text-2xl font-black text-rose-600 mt-1">18 Students</div>
          <div className="text-[10px] text-rose-500 font-bold mt-1">Below 75% Threshold</div>
        </div>

        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-xs">
          <div className="text-xs text-slate-500">Condonation Eligible</div>
          <div className="text-2xl font-black text-amber-700 mt-1">12 Students</div>
          <div className="text-[10px] text-amber-600 font-bold mt-1">Band 65.0% - 74.9%</div>
        </div>
      </div>

      {/* Report Types Selector */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { key: "defaulters", label: "Defaulter Roster (<75%)", icon: AlertTriangle },
          { key: "subject", label: "Subject-Wise Matrix", icon: BookOpen },
          { key: "kitchen", label: "Kitchen Practical Audit", icon: UtensilsCrossed },
          { key: "daily", label: "Daily Register Summary", icon: Calendar },
        ].map((rep) => {
          const Icon = rep.icon;
          const isSelected = selectedReportType === rep.key;
          return (
            <button
              key={rep.key}
              onClick={() => setSelectedReportType(rep.key)}
              className={`p-3.5 rounded-xl border text-left transition-all flex items-center gap-3 ${
                isSelected
                  ? "bg-[#081A2E] text-white border-[#081A2E] shadow-sm"
                  : "bg-white text-slate-700 border-slate-200 hover:bg-slate-50"
              }`}
            >
              <div
                className={`p-2 rounded-lg ${
                  isSelected ? "bg-[#C8A45D] text-slate-950" : "bg-slate-100 text-slate-600"
                }`}
              >
                <Icon className="w-4 h-4" />
              </div>
              <span className="text-xs font-bold leading-snug">{rep.label}</span>
            </button>
          );
        })}
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-3 bg-white p-3.5 rounded-xl border border-slate-200 shadow-xs">
        <div className="relative w-full sm:w-72">
          <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search student or roll number..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-9 pr-3 py-1.5 text-xs rounded-lg border border-slate-200 focus:outline-hidden focus:border-[#C8A45D]"
          />
        </div>

        <div className="flex items-center gap-1.5 text-xs w-full sm:w-auto">
          <span className="font-semibold text-slate-500">Semester:</span>
          {["ALL", 1, 3, 5].map((sem) => (
            <button
              key={String(sem)}
              onClick={() => setSelectedSem(sem as any)}
              className={`px-3 py-1 rounded-lg font-bold text-xs transition-colors ${
                selectedSem === sem
                  ? "bg-[#081A2E] text-white"
                  : "bg-slate-100 text-slate-600 hover:bg-slate-200"
              }`}
            >
              {sem === "ALL" ? "All" : `Sem ${sem}`}
            </button>
          ))}
        </div>
      </div>

      {/* Report Table */}
      <div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead className="bg-[#081A2E] text-slate-200 uppercase tracking-wider text-[10px]">
              <tr>
                <th className="p-3.5">Roll Number</th>
                <th className="p-3.5">Student Name</th>
                <th className="p-3.5">Semester & Group</th>
                <th className="p-3.5">Held</th>
                <th className="p-3.5">Attended</th>
                <th className="p-3.5">Attendance %</th>
                <th className="p-3.5">NCHMCT Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filteredDefaulters.map((d) => (
                <tr key={d.rollNo} className="hover:bg-slate-50/80 transition-colors">
                  <td className="p-3.5 font-mono font-bold text-[#071A4D]">
                    {d.rollNo}
                  </td>
                  <td className="p-3.5 font-bold text-slate-900">
                    {d.name}
                  </td>
                  <td className="p-3.5 text-slate-700">
                    Sem {d.semester} • {d.batch}
                  </td>
                  <td className="p-3.5 font-mono text-slate-600">
                    {d.totalHeld}
                  </td>
                  <td className="p-3.5 font-mono text-slate-800 font-semibold">
                    {d.attended}
                  </td>
                  <td className="p-3.5 font-mono font-bold text-rose-600">
                    {d.percentage}%
                  </td>
                  <td className="p-3.5">
                    <span
                      className={`px-2.5 py-0.5 rounded-full font-bold text-[10px] uppercase ${
                        d.status === "CONDONATION_ELIGIBLE"
                          ? "bg-amber-100 text-amber-900 border border-amber-300"
                          : "bg-rose-100 text-rose-900 border border-rose-300"
                      }`}
                    >
                      {d.status === "CONDONATION_ELIGIBLE"
                        ? "Condonable (65-74%)"
                        : "Detained (<65%)"}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
