"use client";

import React, { useState, useMemo } from "react";
import Link from "next/link";
import {
  Users,
  Search,
  Filter,
  Download,
  Printer,
  Mail,
  Phone,
  CheckCircle2,
  AlertTriangle,
  FileSpreadsheet,
  ArrowRight,
  Sparkles,
} from "lucide-react";
import { toast } from "sonner";

interface RosterStudent {
  id: string;
  rollNumber: string;
  name: string;
  batch: string;
  semester: string;
  email: string;
  phone: string;
  attended: number;
  total: number;
  pct: number;
  condonedUnits: number;
  status: "REGULAR" | "WARNING" | "DEFAULTER";
}

const institutionalStudentsRoster: RosterStudent[] = [
  { id: "s-101", rollNumber: "2441112001", name: "Aaron Smith", batch: "Batch B1", semester: "Sem III", email: "aaron.smith@ihmkolkata.edu.in", phone: "+91 98301 23456", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-102", rollNumber: "2441112002", name: "Bethany Roy", batch: "Batch B1", semester: "Sem III", email: "bethany.roy@ihmkolkata.edu.in", phone: "+91 98301 23457", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-103", rollNumber: "2441112003", name: "Chirag Banerjee", batch: "Batch B1", semester: "Sem III", email: "chirag.b@ihmkolkata.edu.in", phone: "+91 98301 23458", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-104", rollNumber: "2441112004", name: "Devika Sharma", batch: "Batch B1", semester: "Sem III", email: "devika.s@ihmkolkata.edu.in", phone: "+91 98301 23459", attended: 6, total: 9, pct: 66.7, condonedUnits: 4, status: "DEFAULTER" },
  { id: "s-105", rollNumber: "2441112005", name: "Farhan Ahmed", batch: "Batch B1", semester: "Sem III", email: "farhan.a@ihmkolkata.edu.in", phone: "+91 98301 23460", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-106", rollNumber: "2441112006", name: "Gautam Sen", batch: "Batch B1", semester: "Sem III", email: "gautam.s@ihmkolkata.edu.in", phone: "+91 98301 23461", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-107", rollNumber: "2441112007", name: "Harshavardhan Rao", batch: "Batch B1", semester: "Sem III", email: "harsha.rao@ihmkolkata.edu.in", phone: "+91 98301 23462", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-108", rollNumber: "2441112008", name: "Isha Mukherjee", batch: "Batch B1", semester: "Sem III", email: "isha.m@ihmkolkata.edu.in", phone: "+91 98301 23463", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-109", rollNumber: "2441112009", name: "Jayant Verma", batch: "Batch B1", semester: "Sem III", email: "jayant.v@ihmkolkata.edu.in", phone: "+91 98301 23464", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-110", rollNumber: "2441112010", name: "Kritika Das", batch: "Batch B1", semester: "Sem III", email: "kritika.d@ihmkolkata.edu.in", phone: "+91 98301 23465", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-111", rollNumber: "2441112011", name: "Lalit Mohan", batch: "Batch B1", semester: "Sem III", email: "lalit.m@ihmkolkata.edu.in", phone: "+91 98301 23466", attended: 6, total: 9, pct: 66.7, condonedUnits: 0, status: "DEFAULTER" },
  { id: "s-112", rollNumber: "2441112012", name: "Meera Nair", batch: "Batch B1", semester: "Sem III", email: "meera.n@ihmkolkata.edu.in", phone: "+91 98301 23467", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-113", rollNumber: "2441112013", name: "Nikhil Joshi", batch: "Batch B1", semester: "Sem III", email: "nikhil.j@ihmkolkata.edu.in", phone: "+91 98301 23468", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-114", rollNumber: "2441112014", name: "Oindrila Ghosh", batch: "Batch B1", semester: "Sem III", email: "oindrila.g@ihmkolkata.edu.in", phone: "+91 98301 23469", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-115", rollNumber: "2441112015", name: "Prateek Saxena", batch: "Batch B1", semester: "Sem III", email: "prateek.s@ihmkolkata.edu.in", phone: "+91 98301 23470", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-116", rollNumber: "2441112016", name: "Qasim Ali", batch: "Batch B1", semester: "Sem III", email: "qasim.ali@ihmkolkata.edu.in", phone: "+91 98301 23471", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-117", rollNumber: "2441112017", name: "Rhea Chawla", batch: "Batch B1", semester: "Sem III", email: "rhea.c@ihmkolkata.edu.in", phone: "+91 98301 23472", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-118", rollNumber: "2441112018", name: "Sourav Ganguly", batch: "Batch B1", semester: "Sem III", email: "sourav.g@ihmkolkata.edu.in", phone: "+91 98301 23473", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-119", rollNumber: "2441112019", name: "Tanvi Kulkarni", batch: "Batch B1", semester: "Sem III", email: "tanvi.k@ihmkolkata.edu.in", phone: "+91 98301 23474", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-120", rollNumber: "2441112020", name: "Utkarsh Gupta", batch: "Batch B1", semester: "Sem III", email: "utkarsh.g@ihmkolkata.edu.in", phone: "+91 98301 23475", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-121", rollNumber: "2441112021", name: "Varun Mehta", batch: "Batch B1", semester: "Sem III", email: "varun.m@ihmkolkata.edu.in", phone: "+91 98301 23476", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-122", rollNumber: "2441112022", name: "William D'Souza", batch: "Batch B1", semester: "Sem III", email: "william.d@ihmkolkata.edu.in", phone: "+91 98301 23477", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-123", rollNumber: "2441112023", name: "Xavier Pinto", batch: "Batch B1", semester: "Sem III", email: "xavier.p@ihmkolkata.edu.in", phone: "+91 98301 23478", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-124", rollNumber: "2441112024", name: "Yashasvi Paul", batch: "Batch B1", semester: "Sem III", email: "yashasvi.p@ihmkolkata.edu.in", phone: "+91 98301 23479", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-125", rollNumber: "2441112025", name: "Zoya Khan", batch: "Batch B1", semester: "Sem III", email: "zoya.khan@ihmkolkata.edu.in", phone: "+91 98301 23480", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-126", rollNumber: "2441112026", name: "Abhinav Mishra", batch: "Batch B1", semester: "Sem III", email: "abhinav.m@ihmkolkata.edu.in", phone: "+91 98301 23481", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-127", rollNumber: "2441112027", name: "Bhavya Aggarwal", batch: "Batch B1", semester: "Sem III", email: "bhavya.a@ihmkolkata.edu.in", phone: "+91 98301 23482", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-128", rollNumber: "2441112028", name: "Chetan Bhagat", batch: "Batch B1", semester: "Sem III", email: "chetan.b@ihmkolkata.edu.in", phone: "+91 98301 23483", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-129", rollNumber: "2441112029", name: "Deepak Chopra", batch: "Batch B1", semester: "Sem III", email: "deepak.c@ihmkolkata.edu.in", phone: "+91 98301 23484", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-130", rollNumber: "2441112030", name: "Esha Deol", batch: "Batch B1", semester: "Sem III", email: "esha.d@ihmkolkata.edu.in", phone: "+91 98301 23485", attended: 6, total: 9, pct: 66.7, condonedUnits: 0, status: "DEFAULTER" },
];

export default function FacultyRostersPage() {
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<"ALL" | "REGULAR" | "DEFAULTER">("ALL");

  const filtered = useMemo(() => {
    return institutionalStudentsRoster.filter((s) => {
      const q = search.toLowerCase();
      const matchesSearch =
        s.name.toLowerCase().includes(q) ||
        s.rollNumber.includes(q) ||
        s.email.toLowerCase().includes(q);
      const matchesStatus =
        statusFilter === "ALL" ? true : s.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [search, statusFilter]);

  const regularCount = institutionalStudentsRoster.filter((s) => s.status === "REGULAR").length;
  const defaulterCount = institutionalStudentsRoster.filter((s) => s.status === "DEFAULTER").length;

  return (
    <div className="space-y-6 pb-14 font-sans bg-[#F8FAFC]">
      {/* 1. Header & Breadcrumb */}
      <div>
        <div className="flex items-center gap-2 text-xs text-[#64748B] mb-2 font-medium">
          <Link href="/faculty/dashboard" className="hover:text-[#1769E8] transition-colors">
            Faculty Console
          </Link>
          <span>&gt;</span>
          <span>Timetables &amp; Rosters</span>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Enrolled Student Rosters</span>
        </div>

        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <div className="flex items-center gap-2.5">
              <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
                Enrolled Student Rosters
              </h1>
              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-[#DCFCE7] text-[#15803D] border border-[#BBF7D0]">
                {institutionalStudentsRoster.length} Students
              </span>
            </div>
            <p className="text-[14px] text-[#64748B] mt-1 font-normal">
              Course: BHM201 Food Production Operations Practical • Semester III (Batch B1)
            </p>
          </div>

          <div className="flex items-center gap-2.5">
            <button
              onClick={() => toast.success("Printing Official Attendance Shortage Warning Notice...")}
              className="px-3.5 py-2 bg-white border border-[#E2E8F0] hover:bg-slate-50 text-slate-700 rounded-lg text-xs font-semibold flex items-center gap-1.5 shadow-2xs transition-colors"
            >
              <Printer className="w-3.5 h-3.5 text-slate-600" />
              <span>Print Defaulter Notice</span>
            </button>
            <button
              onClick={() => toast.success("Exported Enrolled Student Roster to Excel format.")}
              className="px-4 py-2 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-semibold flex items-center gap-1.5 shadow-xs transition-colors"
            >
              <Download className="w-3.5 h-3.5" />
              <span>Export Roster (.xlsx)</span>
            </button>
          </div>
        </div>
      </div>

      {/* 2. Roster Metrics Ribbon */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5">
        <div className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs flex items-center justify-between">
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Total Enrolled Cohort
            </span>
            <div className="text-2xl font-bold font-heading text-[#071A4D] mt-0.5">
              {institutionalStudentsRoster.length} Students
            </div>
            <span className="text-[11px] text-[#1769E8] font-semibold mt-0.5 block">
              100% Biometric Registered
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-blue-50 text-[#1769E8] flex items-center justify-center shrink-0 border border-blue-100">
            <Users className="w-5 h-5" />
          </div>
        </div>

        <div className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs flex items-center justify-between">
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Eligible &ge;75% Attendance
            </span>
            <div className="text-2xl font-bold font-heading text-emerald-600 mt-0.5">
              {regularCount} Students
            </div>
            <span className="text-[11px] text-emerald-700 font-semibold mt-0.5 block">
              {((regularCount / institutionalStudentsRoster.length) * 100).toFixed(0)}% Safe Compliance
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0 border border-emerald-100">
            <CheckCircle2 className="w-5 h-5" />
          </div>
        </div>

        <div className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs flex items-center justify-between">
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Defaulters &lt;75% Attendance
            </span>
            <div className="text-2xl font-bold font-heading text-amber-600 mt-0.5">
              {defaulterCount} Students
            </div>
            <span className="text-[11px] text-amber-700 font-semibold mt-0.5 block">
              Requires Medical Condonation
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0 border border-amber-100">
            <AlertTriangle className="w-5 h-5" />
          </div>
        </div>
      </div>

      {/* 3. Main Roster Table Card */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
        {/* Controls */}
        <div className="p-4 border-b border-[#E5EAF0] flex flex-col sm:flex-row sm:items-center justify-between gap-3 bg-white">
          <div className="relative flex-1 max-w-sm">
            <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
            <input
              type="text"
              placeholder="Search by student name, roll number, or email..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-9 pr-3 py-1.5 text-xs bg-slate-50 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#1769E8] focus:bg-white transition-colors"
            />
          </div>

          <div className="flex items-center gap-1.5 bg-slate-100 p-1 rounded-lg">
            <button
              onClick={() => setStatusFilter("ALL")}
              className={`px-3 py-1 rounded-md text-xs font-semibold transition-colors ${
                statusFilter === "ALL" ? "bg-white text-[#071A4D] shadow-2xs" : "text-slate-600 hover:text-slate-900"
              }`}
            >
              All ({institutionalStudentsRoster.length})
            </button>
            <button
              onClick={() => setStatusFilter("REGULAR")}
              className={`px-3 py-1 rounded-md text-xs font-semibold transition-colors ${
                statusFilter === "REGULAR" ? "bg-white text-emerald-700 shadow-2xs" : "text-slate-600 hover:text-slate-900"
              }`}
            >
              Regular &ge;75% ({regularCount})
            </button>
            <button
              onClick={() => setStatusFilter("DEFAULTER")}
              className={`px-3 py-1 rounded-md text-xs font-semibold transition-colors ${
                statusFilter === "DEFAULTER" ? "bg-white text-amber-700 shadow-2xs" : "text-slate-600 hover:text-slate-900"
              }`}
            >
              Defaulters &lt;75% ({defaulterCount})
            </button>
          </div>
        </div>

        {/* Table */}
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs border-collapse">
            <thead>
              <tr className="bg-[#F8FAFC] border-b border-[#E5EAF0] text-[#64748B] font-semibold">
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Roll Number</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Student Name &amp; Contact</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Batch Cohort</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Sessions Attended</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Attendance %</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Condonation</th>
                <th className="py-3 px-4 font-bold text-[#071A4D] text-right">Eligibility Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0]">
              {filtered.map((student) => (
                <tr key={student.id} className="hover:bg-[#F8FAFC] transition-colors">
                  <td className="py-3 px-3.5 font-mono font-bold text-[#1769E8]">
                    {student.rollNumber}
                  </td>
                  <td className="py-3 px-3.5">
                    <span className="font-bold text-[#071A4D] text-xs block">
                      {student.name}
                    </span>
                    <span className="text-[11px] text-[#64748B] font-mono">
                      {student.email} • {student.phone}
                    </span>
                  </td>
                  <td className="py-3 px-3.5 font-medium text-[#334155]">
                    {student.batch} ({student.semester})
                  </td>
                  <td className="py-3 px-3.5 text-center font-mono font-bold text-slate-800">
                    {student.attended} / {student.total} Classes
                  </td>
                  <td className="py-3 px-3.5 text-center font-mono font-bold">
                    <span className={student.pct >= 75 ? "text-emerald-600 text-sm" : "text-amber-600 text-sm"}>
                      {student.pct.toFixed(1)}%
                    </span>
                  </td>
                  <td className="py-3 px-3.5 text-center font-mono text-slate-600">
                    {student.condonedUnits > 0 ? (
                      <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-blue-50 text-[#1769E8] border border-blue-200">
                        +{student.condonedUnits}h Med
                      </span>
                    ) : (
                      <span className="text-slate-400">—</span>
                    )}
                  </td>
                  <td className="py-3 px-4 text-right">
                    <span
                      className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold border ${
                        student.status === "REGULAR"
                          ? "bg-[#DCFCE7] text-[#15803D] border-[#BBF7D0]"
                          : "bg-amber-50 text-amber-700 border-amber-200"
                      }`}
                    >
                      {student.status === "REGULAR" ? "Eligible" : "Attendance Shortage"}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
