"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  UserPlus,
  Search,
  Filter,
  CheckCircle2,
  ChevronRight,
  Download,
  Upload,
  Users,
  AlertTriangle,
  Mail,
  Phone,
  FileSpreadsheet,
  X,
} from "lucide-react";
import { toast } from "sonner";

interface StudentRecord {
  id: string;
  rollNo: string;
  name: string;
  program: string;
  semester: number;
  section: string;
  practicalBatch: string;
  attendancePct: number;
  status: "ACTIVE" | "ON_LEAVE" | "DETAINED";
  email: string;
}

export default function DeptAdminStudentsPage() {
  const [students, setStudents] = useState<StudentRecord[]>([
    {
      id: "stu_1",
      rollNo: "2441112001",
      name: "Aarav Sharma",
      program: "B.Sc. in Hospitality & Hotel Administration",
      semester: 1,
      section: "Sec A",
      practicalBatch: "Kitchen Batch K1",
      attendancePct: 88.5,
      status: "ACTIVE",
      email: "aarav.sharma@student.ihm.edu.in",
    },
    {
      id: "stu_2",
      rollNo: "2441112002",
      name: "Ananya Mukherjee",
      program: "B.Sc. in Hospitality & Hotel Administration",
      semester: 1,
      section: "Sec A",
      practicalBatch: "Kitchen Batch K1",
      attendancePct: 92.4,
      status: "ACTIVE",
      email: "ananya.m@student.ihm.edu.in",
    },
    {
      id: "stu_3",
      rollNo: "2441112015",
      name: "Debashis Sen",
      program: "B.Sc. in Hospitality & Hotel Administration",
      semester: 3,
      section: "Sec B",
      practicalBatch: "Kitchen Batch Q1",
      attendancePct: 71.2,
      status: "ACTIVE",
      email: "debashis.sen@student.ihm.edu.in",
    },
    {
      id: "stu_4",
      rollNo: "2441112042",
      name: "Pooja Banerjee",
      program: "B.Sc. in Hospitality & Hotel Administration",
      semester: 3,
      section: "Sec A",
      practicalBatch: "Kitchen Batch Q2",
      attendancePct: 78.6,
      status: "ACTIVE",
      email: "pooja.b@student.ihm.edu.in",
    },
    {
      id: "stu_5",
      rollNo: "2441112089",
      name: "Rahul Roychowdhury",
      program: "B.Sc. in Hospitality & Hotel Administration",
      semester: 5,
      section: "Sec A",
      practicalBatch: "Kitchen Batch A1",
      attendancePct: 67.8,
      status: "ACTIVE",
      email: "rahul.rc@student.ihm.edu.in",
    },
    {
      id: "stu_6",
      rollNo: "2441112095",
      name: "Siddharth Verma",
      program: "B.Sc. in Hospitality & Hotel Administration",
      semester: 5,
      section: "Sec B",
      practicalBatch: "Kitchen Batch A2",
      attendancePct: 83.2,
      status: "ACTIVE",
      email: "siddharth.v@student.ihm.edu.in",
    },
  ]);

  const [search, setSearch] = useState("");
  const [semFilter, setSemFilter] = useState<number | "ALL">("ALL");
  const [isRegisterOpen, setIsRegisterOpen] = useState(false);

  const [formRollNo, setFormRollNo] = useState("");
  const [formName, setFormName] = useState("");
  const [formEmail, setFormEmail] = useState("");
  const [formSem, setFormSem] = useState(1);
  const [formBatch, setFormBatch] = useState("Kitchen Batch K1");

  const filtered = students.filter((s) => {
    const matchesSem = semFilter === "ALL" || s.semester === semFilter;
    const matchesSearch =
      s.name.toLowerCase().includes(search.toLowerCase()) ||
      s.rollNo.includes(search);
    return matchesSem && matchesSearch;
  });

  const handleRegister = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formRollNo.trim() || !formName.trim()) {
      toast.error("Please provide Roll Number and Student Name");
      return;
    }

    const newStudent: StudentRecord = {
      id: `stu_${Date.now()}`,
      rollNo: formRollNo,
      name: formName,
      program: "B.Sc. in Hospitality & Hotel Administration",
      semester: Number(formSem),
      section: "Sec A",
      practicalBatch: formBatch,
      attendancePct: 100,
      status: "ACTIVE",
      email: formEmail || `${formRollNo}@student.ihm.edu.in`,
    };

    setStudents([newStudent, ...students]);
    setIsRegisterOpen(false);
    setFormRollNo("");
    setFormName("");
    setFormEmail("");
    toast.success(`Student ${newStudent.name} registered successfully`);
  };

  const handleExport = () => {
    toast.success("Exported department student roster (CSV)");
  };

  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">Student Registration</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-black text-[#071A4D] tracking-tight">
            Student Registration & Department Roster
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Enroll students, map NCHM roll numbers, and assign practical kitchen batch groups
          </p>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={handleExport}
            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"
          >
            <Download className="w-3.5 h-3.5" />
            <span>Export Roster</span>
          </button>
          <button
            onClick={() => setIsRegisterOpen(true)}
            className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg bg-[#C8A45D] hover:bg-[#B38F48] text-slate-950 font-bold text-xs shadow-sm transition-all"
          >
            <UserPlus className="w-4 h-4" />
            <span>Register Student</span>
          </button>
        </div>
      </div>

      {/* Filter and Search */}
      <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-80">
          <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search by student name or NCHM roll..."
            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">Filter Semester:</span>
          {["ALL", 1, 3, 5].map((sem) => (
            <button
              key={String(sem)}
              onClick={() => setSemFilter(sem as any)}
              className={`px-3 py-1 rounded-lg font-bold text-xs transition-colors ${
                semFilter === sem
                  ? "bg-[#081A2E] text-white"
                  : "bg-slate-100 text-slate-600 hover:bg-slate-200"
              }`}
            >
              {sem === "ALL" ? "All" : `Sem ${sem}`}
            </button>
          ))}
        </div>
      </div>

      {/* Students 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">NCHM Roll No</th>
                <th className="p-3.5">Student Name</th>
                <th className="p-3.5">Semester & Program</th>
                <th className="p-3.5">Practical Batch</th>
                <th className="p-3.5">Overall Attendance</th>
                <th className="p-3.5">NCHM Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filtered.map((s) => (
                <tr key={s.id} className="hover:bg-slate-50/80 transition-colors">
                  <td className="p-3.5 font-mono font-bold text-[#071A4D]">
                    {s.rollNo}
                  </td>
                  <td className="p-3.5">
                    <div className="font-bold text-slate-900">{s.name}</div>
                    <div className="text-[11px] text-slate-400">{s.email}</div>
                  </td>
                  <td className="p-3.5 text-slate-700">
                    <div>Semester {s.semester} • {s.section}</div>
                    <div className="text-[10px] text-slate-400 truncate max-w-xs">{s.program}</div>
                  </td>
                  <td className="p-3.5">
                    <span className="px-2.5 py-0.5 rounded-full font-bold text-[10px] bg-amber-50 text-[#785E2F] border border-amber-200">
                      {s.practicalBatch}
                    </span>
                  </td>
                  <td className="p-3.5 font-mono font-bold">
                    <span
                      className={
                        s.attendancePct >= 75
                          ? "text-emerald-700"
                          : "text-rose-600"
                      }
                    >
                      {s.attendancePct}%
                    </span>
                  </td>
                  <td className="p-3.5">
                    <span
                      className={`px-2 py-0.5 rounded-full font-bold text-[10px] uppercase ${
                        s.attendancePct >= 75
                          ? "bg-emerald-100 text-emerald-800"
                          : "bg-rose-100 text-rose-800"
                      }`}
                    >
                      {s.attendancePct >= 75 ? "Eligible" : "Defaulter (<75%)"}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Register Modal */}
      {isRegisterOpen && (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl border border-slate-200">
            <div className="flex items-center justify-between pb-3 border-b border-slate-100">
              <h3 className="font-bold text-base text-[#071A4D]">Register New Student</h3>
              <button onClick={() => setIsRegisterOpen(false)}>
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>

            <form onSubmit={handleRegister} className="space-y-4 pt-4 text-xs">
              <div>
                <label className="font-bold text-slate-800 block mb-1">NCHM Roll Number *</label>
                <input
                  type="text"
                  placeholder="e.g. 2441112105"
                  value={formRollNo}
                  onChange={(e) => setFormRollNo(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                  required
                />
              </div>

              <div>
                <label className="font-bold text-slate-800 block mb-1">Student Full Name *</label>
                <input
                  type="text"
                  placeholder="e.g. Sayan Mukherjee"
                  value={formName}
                  onChange={(e) => setFormName(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                  required
                />
              </div>

              <div>
                <label className="font-bold text-slate-800 block mb-1">Official Email</label>
                <input
                  type="email"
                  placeholder="sayan@student.ihm.edu.in"
                  value={formEmail}
                  onChange={(e) => setFormEmail(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Semester</label>
                  <select
                    value={formSem}
                    onChange={(e) => setFormSem(Number(e.target.value))}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                  >
                    {[1, 2, 3, 4, 5, 6].map((s) => (
                      <option key={s} value={s}>
                        Semester {s}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Practical Batch</label>
                  <select
                    value={formBatch}
                    onChange={(e) => setFormBatch(e.target.value)}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                  >
                    <option value="Kitchen Batch K1">Kitchen Batch K1</option>
                    <option value="Kitchen Batch K2">Kitchen Batch K2</option>
                    <option value="Bakery Batch B1">Bakery Batch B1</option>
                    <option value="Quantity Batch Q1">Quantity Batch Q1</option>
                    <option value="Advanced Batch A1">Advanced Batch A1</option>
                  </select>
                </div>
              </div>

              <div className="pt-3 border-t border-slate-100 flex justify-end gap-2">
                <button
                  type="button"
                  onClick={() => setIsRegisterOpen(false)}
                  className="px-4 py-2 rounded-lg border border-slate-200 font-bold text-slate-600 hover:bg-slate-50"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 rounded-lg bg-[#C8A45D] text-slate-950 font-bold hover:bg-[#B38F48]"
                >
                  Register Student
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
