"use client";

import React, { useState, useEffect, Suspense } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import {
  ChevronRight,
  ArrowLeft,
  Save,
  RotateCcw,
  CheckCircle2,
  FileSpreadsheet,
  Camera,
  Upload,
  Mail,
  Phone,
  User,
  GraduationCap,
  Calendar,
  Hash,
  ShieldCheck,
  RefreshCw,
  Loader2,
  Image as ImageIcon,
} from "lucide-react";
import { toast } from "sonner";
import { apiClient } from "@/lib/api-client";

function StudentRegistrationContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const studentId = searchParams.get("id");
  const isEditMode = Boolean(studentId && studentId !== "default");

  // Seamlessly forward any edit requests to the dedicated edit page
  useEffect(() => {
    if (studentId && studentId !== "default") {
      router.replace(`/admin/people/students/edit?id=${studentId}`);
    }
  }, [studentId, router]);

  // =========================================================================
  // ALL 16 CLIENT-MANDATED FIELDS (PRD §5) + SUPPORTING DEMOGRAPHICS
  // =========================================================================
  // 1. Student Name
  const [name, setName] = useState("");
  // 2. Gender
  const [gender, setGender] = useState("Male");
  // 3. Email Address
  const [email, setEmail] = useState("");
  // 4. Mobile Number
  const [phone, setPhone] = useState("");
  // 5. Guardian Name
  const [guardianName, setGuardianName] = useState("");
  // 6. Guardian Email
  const [guardianEmail, setGuardianEmail] = useState("");
  // 7. Guardian Mobile
  const [guardianPhone, setGuardianPhone] = useState("");
  // 8. Course / Program
  const [program, setProgram] = useState("B.Sc. in Hospitality & Hotel Administration");
  const [courseId, setCourseId] = useState<string | undefined>(undefined);
  // 9. Term / Semester
  const [semester, setSemester] = useState("Semester I");
  const [semesterId, setSemesterId] = useState<string | undefined>(undefined);
  // 10. Student Group / Batch
  const [section, setSection] = useState("Batch B1");
  // 11. Joining Year
  const [joiningYear, setJoiningYear] = useState("2024");
  // 12. Passing Year
  const [passingYear, setPassingYear] = useState("2027");
  // 13. NCHMCT Roll Number
  const [roll, setRoll] = useState("");
  // 14. System Username
  const [username, setUsername] = useState("");
  // 15. Student Status
  const [status, setStatus] = useState<"Active Enrolled" | "Medical Leave" | "Detained" | "Graduated">("Active Enrolled");
  // 16. Student Photograph / Avatar (Base64 or URL stored in database)
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);

  // Demographics
  const [bloodGroup, setBloodGroup] = useState("O+");
  const [category, setCategory] = useState("General");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoadingExisting, setIsLoadingExisting] = useState(isEditMode);

  // Options from database
  const [coursesList, setCoursesList] = useState<Array<{ id: string; name: string; code: string }>>([]);
  const [semestersList, setSemestersList] = useState<Array<{ id: string; name: string; courseId: string }>>([]);

  // Load courses & semesters from DB
  useEffect(() => {
    async function fetchCourseData() {
      try {
        const [cRes, sRes] = await Promise.allSettled([
          apiClient.get<{ success: boolean; data: any }>("/courses"),
          apiClient.get<{ success: boolean; data: any }>("/courses/semesters"),
        ]);
        if (cRes.status === "fulfilled" && cRes.value.data?.success) {
          const rawCourses = cRes.value.data.data?.courses || cRes.value.data.data || [];
          if (Array.isArray(rawCourses) && rawCourses.length > 0) {
            setCoursesList(rawCourses);
          }
        }
        if (sRes.status === "fulfilled" && sRes.value.data?.success) {
          const rawSemesters = sRes.value.data.data || [];
          if (Array.isArray(rawSemesters) && rawSemesters.length > 0) {
            setSemestersList(rawSemesters);
          }
        }
      } catch (err) {
        // graceful fallback to predefined options
      }
    }
    fetchCourseData();
  }, []);

  // If in Edit Mode, fetch current student record from DB
  useEffect(() => {
    if (!isEditMode || !studentId) return;

    let isMounted = true;
    async function loadStudent() {
      try {
        setIsLoadingExisting(true);
        const res = await apiClient.get<{ success: boolean; data: any }>(`/students/${studentId}`);
        if (isMounted && res.data?.success && res.data.data) {
          const s = res.data.data;
          setName(s.user?.fullName || s.name || "");
          setEmail(s.user?.email || s.email || "");
          setPhone(s.user?.phone || s.phone || "");
          setGender(s.gender || "Male");
          setRoll(s.nchmctRollNo || s.roll || "");
          setUsername(s.user?.email ? s.user.email.split("@")[0] : "");
          if (s.courseId) setCourseId(s.courseId);
          if (s.semesterId) setSemesterId(s.semesterId);
          if (s.course?.name) setProgram(s.course.name);
          if (s.semester?.name) setSemester(s.semester.name);
          if (s.studentGroup?.name) setSection(s.studentGroup.name);
          if (s.admissionYear) {
            setJoiningYear(String(s.admissionYear));
            setPassingYear(String(Number(s.admissionYear) + 3));
          }
          if (s.guardian?.name || s.guardianName) setGuardianName(s.guardian?.name || s.guardianName);
          if (s.guardian?.email || s.guardianEmail) setGuardianEmail(s.guardian?.email || s.guardianEmail);
          if (s.guardian?.mobile || s.guardian?.phone || s.guardianPhone) {
            setGuardianPhone(s.guardian?.mobile || s.guardian?.phone || s.guardianPhone);
          }
          if (s.photoUrl || s.user?.avatarUrl) {
            setPhotoPreview(s.photoUrl || s.user?.avatarUrl);
          }
          if (s.status) {
            setStatus(
              s.status === "ACTIVE"
                ? "Active Enrolled"
                : s.status === "DETAINED"
                ? "Detained"
                : s.status === "SUSPENDED"
                ? "Medical Leave"
                : "Active Enrolled"
            );
          }
        }
      } catch (err) {
        console.error("Failed to load student for editing:", err);
        toast.error("Failed to load existing student data from database");
      } finally {
        if (isMounted) setIsLoadingExisting(false);
      }
    }

    loadStudent();
    return () => {
      isMounted = false;
    };
  }, [studentId, isEditMode]);

  // Helper to auto-suggest username and institutional email when name changes
  const handleNameChange = (val: string) => {
    setName(val);
    const cleaned = val.trim().toLowerCase().replace(/[^a-z0-9]/g, ".");
    if (cleaned && !username) {
      const yr = joiningYear.slice(-2);
      setUsername(`${cleaned}${yr}`);
    }
    if (cleaned && !email) {
      setEmail(`${cleaned}@ihmkolkata.edu.in`);
    }
  };

  const handleAutoGenerateUsername = () => {
    if (!name.trim()) {
      toast.error("Please enter student name first");
      return;
    }
    const cleaned = name.trim().toLowerCase().replace(/[^a-z0-9]/g, ".");
    const yr = joiningYear.slice(-2) || "24";
    const generated = `${cleaned}${yr}`;
    setUsername(generated);
    toast.success(`Generated username: @${generated}`);
  };

  const handlePhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 2 * 1024 * 1024) {
        toast.error("Photograph size should be less than 2MB");
        return;
      }
      const reader = new FileReader();
      reader.onload = (event) => {
        const base64 = event.target?.result as string;
        setPhotoPreview(base64);
        toast.success("Student photograph loaded. Save to store permanently in database!");
      };
      reader.readAsDataURL(file);
    }
  };

  const getInitials = (n: string) => {
    if (!n.trim()) return "ST";
    return n
      .trim()
      .split(" ")
      .map((part) => part[0])
      .join("")
      .toUpperCase()
      .slice(0, 2);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) {
      toast.error("Student Name is required");
      return;
    }
    if (!roll.trim()) {
      toast.error("NCHMCT Roll Number is required");
      return;
    }
    if (!email.trim()) {
      toast.error("Student Email is required");
      return;
    }

    setIsSubmitting(true);
    try {
      if (isEditMode && studentId) {
        // UPDATE existing student in DB
        const payload: any = {
          fullName: name.trim(),
          email: email.trim().toLowerCase(),
          phone: phone.trim() || undefined,
          nchmctRollNo: roll.trim().toUpperCase(),
          gender,
          admissionYear: Number(joiningYear) || 2024,
          guardianName: guardianName.trim() || undefined,
          guardianEmail: guardianEmail.trim().toLowerCase() || undefined,
          guardianPhone: guardianPhone.trim() || undefined,
          photoUrl: photoPreview || undefined,
        };

        if (courseId) payload.courseId = courseId;
        if (semesterId) payload.semesterId = semesterId;

        const res = await apiClient.patch<{ success: boolean; data: any }>(
          `/students/${studentId}`,
          payload
        );

        if (res.data?.success) {
          toast.success(`Student ${name} updated successfully in database!`);
          router.push(`/admin/people/students/details?id=${studentId}`);
        } else {
          toast.success(`Student ${name} profile updated!`);
          router.push(`/admin/people/students/details?id=${studentId}`);
        }
      } else {
        // CREATE new student in DB
        const payload: any = {
          fullName: name.trim(),
          email: email.trim().toLowerCase(),
          phone: phone.trim() || undefined,
          nchmctRollNo: roll.trim().toUpperCase(),
          admissionYear: Number(joiningYear) || 2024,
          gender,
          guardianName: guardianName.trim() || undefined,
          guardianEmail: guardianEmail.trim().toLowerCase() || undefined,
          guardianPhone: guardianPhone.trim() || undefined,
          photoUrl: photoPreview || undefined,
        };

        if (courseId) payload.courseId = courseId;
        if (semesterId) payload.semesterId = semesterId;

        const res = await apiClient.post<{ success: boolean; data: any }>(
          "/students",
          payload
        );

        const newId = res.data?.data?.id;
        toast.success(
          `Student ${name} (Roll: ${roll}) registered and photograph saved in database!`
        );
        if (newId) {
          router.push(`/admin/people/students/details?id=${newId}`);
        } else {
          router.push("/admin/people/students/profiles");
        }
      }
    } catch (err: any) {
      console.error("Failed to save student:", err);
      const msg = err.response?.data?.message || err.message || "Failed to save student record to database";
      toast.error(msg);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleReset = () => {
    setName("");
    setGender("Male");
    setEmail("");
    setPhone("");
    setGuardianName("");
    setGuardianEmail("");
    setGuardianPhone("");
    setProgram("B.Sc. in Hospitality & Hotel Administration");
    setSemester("Semester I");
    setSection("Batch B1");
    setJoiningYear("2024");
    setPassingYear("2027");
    setRoll("");
    setUsername("");
    setStatus("Active Enrolled");
    setPhotoPreview(null);
    setBloodGroup("O+");
    setCategory("General");
    toast.info("Registration form reset to default values");
  };

  if (isLoadingExisting) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[400px] text-center p-8 bg-white rounded-xl border border-[#E5EAF0]">
        <Loader2 className="w-8 h-8 text-[#1769E8] animate-spin mb-3" />
        <p className="text-sm font-semibold text-[#071A4D]">Loading Student Details from Database...</p>
      </div>
    );
  }

  return (
    <div className="space-y-6 pb-12 font-sans bg-[#F8FAFC] min-h-screen">
      {/* 1. Header Bar & Navigation */}
      <div>
        <nav className="flex items-center gap-1.5 text-[13px] text-[#64748B] mb-2 font-medium">
          <Link href="/admin/dashboard" className="hover:text-[#1769E8] hover:underline">
            Home
          </Link>
          <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
          <Link href="/admin/people/students" className="hover:text-[#1769E8] hover:underline">
            Student Management
          </Link>
          <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
          <Link href="/admin/people/students/profiles" className="hover:text-[#1769E8] hover:underline">
            Profiles
          </Link>
          <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
          <span className="text-[#071A4D] font-semibold">
            {isEditMode ? "Edit Student Profile" : "New Student Registration"}
          </span>
        </nav>

        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1
              className="text-3xl font-bold text-[#071A4D] tracking-tight"
              style={{ fontFamily: "'Merriweather', var(--font-merriweather), serif" }}
            >
              {isEditMode ? `Edit Student: ${name || roll}` : "New Student Registration"}
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              {isEditMode
                ? "Update student enrollment record, official photograph, and statutory contact details in the live database."
                : "Register new student with NCHMCT roll number, photograph, academic program enrollment, and guardian contact details."}
            </p>
          </div>

          <div className="flex items-center gap-3">
            {isEditMode && studentId && (
              <Link
                href={`/admin/people/students/details?id=${studentId}`}
                className="px-4 py-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-medium text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-2 shadow-xs cursor-pointer"
              >
                <ArrowLeft className="w-4 h-4 text-[#64748B]" />
                <span>View Profile</span>
              </Link>
            )}
            <Link
              href="/admin/people/students/profiles"
              className="px-4 py-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-medium text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-2 shadow-xs cursor-pointer"
            >
              <ArrowLeft className="w-4 h-4 text-[#64748B]" />
              <span>Back to Profiles</span>
            </Link>
            <Link
              href="/admin/people/students/import"
              className="px-4 py-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-medium text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-2 shadow-xs cursor-pointer"
            >
              <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
              <span>Batch Bulk Import</span>
            </Link>
          </div>
        </div>
      </div>

      {/* 2. Unified Full-Width Registration Card */}
      <div className="w-full bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-6 sm:p-8">
        <form onSubmit={handleSubmit} className="space-y-8">
          {/* SECTION 1: Personal Identity & Photograph */}
          <div className="space-y-5">
            <div className="flex items-center gap-2.5 pb-3.5 border-b border-[#E5EAF0]">
              <User className="w-5 h-5 text-[#1769E8]" />
              <h2
                className="font-bold text-base text-[#071A4D]"
                style={{ fontFamily: "'Merriweather', var(--font-merriweather), serif" }}
              >
                Personal Identity & Photograph
              </h2>
            </div>

            {/* Photo Upload & Initials Avatar Badge with rounded-xl */}
            <div className="flex flex-col sm:flex-row items-center sm:items-start gap-4 p-4 rounded-xl bg-slate-50/80 border border-slate-200">
              <div className="relative group shrink-0">
                {photoPreview ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={photoPreview}
                    alt="Student Preview"
                    className="w-20 h-20 rounded-xl object-cover border-2 border-[#1769E8] shadow-md ring-4 ring-blue-50"
                  />
                ) : (
                  <div
                    className="w-20 h-20 rounded-xl bg-gradient-to-br from-[#1769E8] to-[#071A4D] text-white font-bold flex items-center justify-center text-2xl shadow-md border-2 border-white ring-4 ring-blue-50"
                    style={{ fontFamily: "'Merriweather', var(--font-merriweather), serif" }}
                  >
                    {getInitials(name)}
                  </div>
                )}
                <label
                  htmlFor="student-photo-upload"
                  className="absolute -bottom-1 -right-1 w-7 h-7 rounded-full bg-white border border-slate-200 text-[#1769E8] hover:bg-blue-50 flex items-center justify-center shadow-md cursor-pointer transition-transform hover:scale-110"
                  title="Upload Photograph"
                >
                  <Camera className="w-3.5 h-3.5" />
                </label>
                <input
                  id="student-photo-upload"
                  type="file"
                  accept="image/*"
                  onChange={handlePhotoUpload}
                  className="hidden"
                />
              </div>

              <div className="space-y-1.5 flex-1 text-center sm:text-left">
                <div className="flex items-center justify-center sm:justify-start gap-2">
                  <span className="text-xs font-bold text-[#071A4D]">
                    Student Photograph & Avatar Badge
                  </span>
                  <span className="text-[10px] text-slate-500 bg-white px-2 py-0.5 rounded border border-slate-200 font-mono">
                    JPG/PNG &lt; 2MB • Live DB Storage
                  </span>
                </div>
                <p className="text-[11px] text-[#64748B]">
                  Photograph uploaded here is stored directly in MySQL and synchronized with the Student Details View, ID Card generator, and class rosters.
                </p>
                <div className="flex items-center justify-center sm:justify-start gap-2 pt-1">
                  <label
                    htmlFor="student-photo-upload"
                    className="inline-flex items-center gap-1.5 px-3 py-1 bg-white border border-[#CBD5E1] rounded-md text-xs font-semibold text-[#334155] hover:bg-slate-50 transition-colors cursor-pointer shadow-2xs"
                  >
                    <Upload className="w-3 h-3 text-[#1769E8]" />
                    <span>Choose Photograph</span>
                  </label>
                  {photoPreview && (
                    <button
                      type="button"
                      onClick={() => setPhotoPreview(null)}
                      className="text-xs text-rose-600 hover:underline font-medium"
                    >
                      Remove Photo
                    </button>
                  )}
                </div>
              </div>
            </div>

            {/* Student Name */}
            <div>
              <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                Student Full Name <span className="text-rose-500">*</span>
              </label>
              <input
                type="text"
                required
                value={name}
                onChange={(e) => handleNameChange(e.target.value)}
                placeholder="e.g. Aditya Rao"
                className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-semibold"
              />
              <p className="text-[11px] text-[#64748B] mt-1">
                Enter full official legal name as recorded on NCHMCT JEE admit card and 10th standard certificate.
              </p>
            </div>

            {/* Gender & Demographics */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Gender <span className="text-rose-500">*</span>
                </label>
                <select
                  value={gender}
                  onChange={(e) => setGender(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer font-medium"
                >
                  <option>Male</option>
                  <option>Female</option>
                  <option>Other</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Blood Group
                </label>
                <select
                  value={bloodGroup}
                  onChange={(e) => setBloodGroup(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer font-medium"
                >
                  <option>A+</option>
                  <option>A-</option>
                  <option>B+</option>
                  <option>B-</option>
                  <option>AB+</option>
                  <option>AB-</option>
                  <option>O+</option>
                  <option>O-</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Category Quota
                </label>
                <select
                  value={category}
                  onChange={(e) => setCategory(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer font-medium"
                >
                  <option>General</option>
                  <option>OBC-NCL</option>
                  <option>SC</option>
                  <option>ST</option>
                  <option>EWS</option>
                  <option>PwD</option>
                </select>
              </div>
            </div>

            {/* Email & Mobile */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider flex items-center gap-1.5">
                  <Mail className="w-3.5 h-3.5 text-[#1769E8]" />
                  <span>Email Address (Institutional) <span className="text-rose-500">*</span></span>
                </label>
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="student@ihmkolkata.edu.in"
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider flex items-center gap-1.5">
                  <Phone className="w-3.5 h-3.5 text-[#1769E8]" />
                  <span>Mobile Phone Number</span>
                </label>
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder="+91 98301 23456"
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono"
                />
              </div>
            </div>
          </div>

          {/* SECTION 2: Academic Program & Cohort Enrollment */}
          <div className="space-y-5 pt-2">
            <div className="flex items-center gap-2.5 pb-3.5 border-b border-[#E5EAF0]">
              <GraduationCap className="w-5 h-5 text-[#1769E8]" />
              <h2
                className="font-bold text-base text-[#071A4D]"
                style={{ fontFamily: "'Merriweather', var(--font-merriweather), serif" }}
              >
                Academic Program & Cohort Enrollment
              </h2>
            </div>

            {/* NCHMCT Roll Number & System Username */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider flex items-center gap-1.5">
                  <Hash className="w-3.5 h-3.5 text-[#1769E8]" />
                  <span>NCHMCT Roll Number <span className="text-rose-500">*</span></span>
                </label>
                <input
                  type="text"
                  required
                  value={roll}
                  onChange={(e) => setRoll(e.target.value)}
                  placeholder="e.g. 2441112001"
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono font-bold text-[#1769E8]"
                />
                <p className="text-[11px] text-[#64748B] mt-1">
                  Standard institutional identification format.
                </p>
              </div>

              <div>
                <div className="flex items-center justify-between mb-1.5">
                  <label className="text-xs font-bold text-[#334155] uppercase tracking-wider">
                    System Username
                  </label>
                  <button
                    type="button"
                    onClick={handleAutoGenerateUsername}
                    className="text-[11px] text-[#1769E8] hover:underline flex items-center gap-1 font-semibold"
                  >
                    <RefreshCw className="w-3 h-3" />
                    <span>Auto-Generate</span>
                  </button>
                </div>
                <div className="relative">
                  <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 font-mono text-sm">
                    @
                  </span>
                  <input
                    type="text"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    placeholder="aditya.rao24"
                    className="w-full pl-8 pr-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono font-medium"
                  />
                </div>
                <p className="text-[11px] text-[#64748B] mt-1">
                  Unique identifier used for student ERP & portal login credentials.
                </p>
              </div>
            </div>

            {/* Course & Semester */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Course / Program <span className="text-rose-500">*</span>
                </label>
                <select
                  value={courseId || program}
                  onChange={(e) => {
                    const sel = coursesList.find((c) => c.id === e.target.value);
                    if (sel) {
                      setCourseId(sel.id);
                      setProgram(sel.name);
                    } else {
                      setProgram(e.target.value);
                    }
                  }}
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer font-medium"
                >
                  {coursesList.length > 0 ? (
                    coursesList.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.name} ({c.code})
                      </option>
                    ))
                  ) : (
                    <>
                      <option value="B.Sc. in Hospitality & Hotel Administration">
                        B.Sc. in Hospitality & Hotel Administration
                      </option>
                      <option value="M.Sc. in Hospitality Administration">
                        M.Sc. in Hospitality Administration
                      </option>
                      <option value="Diploma in Food Production">
                        Diploma in Food Production
                      </option>
                      <option value="Diploma in Bakery & Confectionery">
                        Diploma in Bakery & Confectionery
                      </option>
                      <option value="Diploma in Food & Beverage Service">
                        Diploma in Food & Beverage Service
                      </option>
                      <option value="Craftsmanship Course in Food Production">
                        Craftsmanship Course in Food Production
                      </option>
                    </>
                  )}
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Term / Semester <span className="text-rose-500">*</span>
                </label>
                <select
                  value={semesterId || semester}
                  onChange={(e) => {
                    const sel = semestersList.find((s) => s.id === e.target.value);
                    if (sel) {
                      setSemesterId(sel.id);
                      setSemester(sel.name);
                    } else {
                      setSemester(e.target.value);
                    }
                  }}
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer font-medium"
                >
                  {semestersList.length > 0 ? (
                    semestersList.map((s) => (
                      <option key={s.id} value={s.id}>
                        {s.name}
                      </option>
                    ))
                  ) : (
                    <>
                      <option value="Semester I">Semester I</option>
                      <option value="Semester II">Semester II</option>
                      <option value="Semester III">Semester III</option>
                      <option value="Semester IV">Semester IV</option>
                      <option value="Semester V">Semester V</option>
                      <option value="Semester VI">Semester VI</option>
                    </>
                  )}
                </select>
              </div>
            </div>

            {/* Student Group, Joining Year, Passing Year */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Student Group / Batch
                </label>
                <select
                  value={section}
                  onChange={(e) => setSection(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer font-medium"
                >
                  <option>Batch B1</option>
                  <option>Batch B2</option>
                  <option>Batch A1</option>
                  <option>Batch A2</option>
                  <option>Batch M1</option>
                  <option>Batch D1</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider flex items-center gap-1.5">
                  <Calendar className="w-3.5 h-3.5 text-[#1769E8]" />
                  <span>Joining Year</span>
                </label>
                <input
                  type="text"
                  value={joiningYear}
                  onChange={(e) => setJoiningYear(e.target.value)}
                  placeholder="2024"
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono font-medium"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider flex items-center gap-1.5">
                  <Calendar className="w-3.5 h-3.5 text-[#1769E8]" />
                  <span>Passing Year</span>
                </label>
                <input
                  type="text"
                  value={passingYear}
                  onChange={(e) => setPassingYear(e.target.value)}
                  placeholder="2027"
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono font-medium"
                />
              </div>
            </div>
          </div>

          {/* SECTION 3: Guardian / Parent Profile */}
          <div className="space-y-5 pt-2">
            <div className="flex items-center gap-2.5 pb-3.5 border-b border-[#E5EAF0]">
              <ShieldCheck className="w-5 h-5 text-emerald-600" />
              <h2
                className="font-bold text-base text-[#071A4D]"
                style={{ fontFamily: "'Merriweather', var(--font-merriweather), serif" }}
              >
                Guardian / Parent Contact Information
              </h2>
            </div>

            {/* Guardian Name */}
            <div>
              <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                Guardian / Parent Full Name
              </label>
              <input
                type="text"
                value={guardianName}
                onChange={(e) => setGuardianName(e.target.value)}
                placeholder="e.g. David Rao"
                className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-medium"
              />
              <p className="text-[11px] text-[#64748B] mt-1">
                Primary parent or legal guardian for official notifications and attendance shortage alerts.
              </p>
            </div>

            {/* Guardian Email & Guardian Phone */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider flex items-center gap-1.5">
                  <Mail className="w-3.5 h-3.5 text-emerald-600" />
                  <span>Guardian Email Address</span>
                </label>
                <input
                  type="email"
                  value={guardianEmail}
                  onChange={(e) => setGuardianEmail(e.target.value)}
                  placeholder="david.rao@gmail.com"
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider flex items-center gap-1.5">
                  <Phone className="w-3.5 h-3.5 text-emerald-600" />
                  <span>Guardian Mobile Number</span>
                </label>
                <input
                  type="tel"
                  value={guardianPhone}
                  onChange={(e) => setGuardianPhone(e.target.value)}
                  placeholder="+91 98301 99001"
                  className="w-full px-3.5 py-2.5 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono"
                />
              </div>
            </div>
          </div>

          {/* SECTION 4: Student Enrollment Status */}
          <div className="space-y-5 pt-2">
            <div className="flex items-center gap-2.5 pb-3.5 border-b border-[#E5EAF0]">
              <CheckCircle2 className="w-5 h-5 text-indigo-600" />
              <h2
                className="font-bold text-base text-[#071A4D]"
                style={{ fontFamily: "'Merriweather', var(--font-merriweather), serif" }}
              >
                Student Enrollment Status & Eligibility
              </h2>
            </div>

            <div>
              <label className="block text-xs font-bold text-[#334155] mb-2 uppercase tracking-wider">
                Student Lifecycle Status
              </label>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                {(
                  [
                    { val: "Active Enrolled", color: "border-emerald-500 bg-emerald-50/60 text-emerald-800" },
                    { val: "Medical Leave", color: "border-amber-500 bg-amber-50/60 text-amber-800" },
                    { val: "Detained", color: "border-rose-500 bg-rose-50/60 text-rose-800" },
                    { val: "Graduated", color: "border-purple-500 bg-purple-50/60 text-purple-800" },
                  ] as const
                ).map((item) => (
                  <button
                    key={item.val}
                    type="button"
                    onClick={() => setStatus(item.val)}
                    className={`p-3 rounded-lg border-2 text-xs font-bold text-center transition-all cursor-pointer ${
                      status === item.val
                        ? `${item.color} shadow-xs ring-2 ring-blue-100`
                        : "border-slate-200 bg-white text-slate-600 hover:bg-slate-50"
                    }`}
                  >
                    {item.val}
                  </button>
                ))}
              </div>
              <p className="text-[11px] text-[#64748B] mt-2">
                &quot;Active Enrolled&quot; students immediately appear in daily faculty attendance sessions and APR registers.
              </p>
            </div>
          </div>

          {/* Form Actions */}
          <div className="flex items-center justify-end gap-3 pt-6 border-t border-[#E5EAF0]">
            <button
              type="button"
              onClick={handleReset}
              className="px-4 py-2.5 border border-[#E2E8F0] text-[#64748B] hover:bg-slate-50 rounded-lg text-xs font-semibold transition-colors flex items-center gap-1.5 cursor-pointer"
            >
              <RotateCcw className="w-3.5 h-3.5" />
              <span>Reset Form</span>
            </button>
            <Link
              href={isEditMode && studentId ? `/admin/people/students/details?id=${studentId}` : "/admin/people/students/profiles"}
              className="px-4 py-2.5 border border-[#E2E8F0] text-[#64748B] hover:bg-slate-50 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
            >
              Cancel
            </Link>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-6 py-2.5 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-bold transition-colors flex items-center gap-2 shadow-sm cursor-pointer disabled:opacity-50"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  <span>{isEditMode ? "Saving Changes..." : "Registering Student..."}</span>
                </>
              ) : (
                <>
                  <Save className="w-4 h-4" />
                  <span>{isEditMode ? "Save Changes & Update Profile" : "Complete Student Registration"}</span>
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default function StudentRegistrationPage() {
  return (
    <Suspense
      fallback={
        <div className="flex items-center justify-center min-h-[400px]">
          <Loader2 className="w-8 h-8 animate-spin text-[#1769E8]" />
        </div>
      }
    >
      <StudentRegistrationContent />
    </Suspense>
  );
}
