"use client";

import React, { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  ChevronRight,
  ArrowLeft,
  Save,
  RotateCcw,
  CheckCircle2,
  FileSpreadsheet,
  Camera,
  Upload,
  Mail,
  Phone,
  User,
  GraduationCap,
  Calendar,
  Hash,
  ShieldCheck,
  RefreshCw,
  Clock,
  BookOpen,
  KeyRound,
  Eye,
  EyeOff,
  Building2,
  Sparkles,
  Users,
  Layers,
  CalendarDays,
  UtensilsCrossed,
  DoorOpen,
} from "lucide-react";
import { toast } from "sonner";

interface AvailableSubject {
  code: string;
  name: string;
  type: "Theory" | "Practical" | "Both";
  department: string;
  hours: number;
}

const AVAILABLE_SUBJECTS: AvailableSubject[] = [
  { code: "BHM111", name: "Food Production Foundation I", type: "Both", department: "Food Production", hours: 6 },
  { code: "BHM112", name: "Food & Beverage Service Operations", type: "Both", department: "F&B Service", hours: 6 },
  { code: "BHM113", name: "Front Office Foundation", type: "Theory", department: "Front Office", hours: 3 },
  { code: "BHM114", name: "Accommodation Operations I", type: "Both", department: "Housekeeping", hours: 4 },
  { code: "BHM211", name: "Quantity Food Kitchen (QFK)", type: "Practical", department: "Food Production", hours: 8 },
  { code: "BHM212", name: "Beverage Studies & Mixology", type: "Both", department: "F&B Service", hours: 4 },
  { code: "BHM311", name: "Advanced Culinary Arts & International Cuisine", type: "Both", department: "Food Production", hours: 8 },
  { code: "BHM312", name: "Hospitality Marketing & Revenue Management", type: "Theory", department: "Management", hours: 4 },
  { code: "BHM313", name: "Bakery & Confectionery Craft II", type: "Practical", department: "Food Production", hours: 6 },
  { code: "BHM314", name: "Hotel Engineering & Maintenance", type: "Theory", department: "Management", hours: 3 },
];

const DEPARTMENTS = [
  "Food Production",
  "F&B Service",
  "Front Office",
  "Housekeeping",
  "Bakery & Confectionery",
  "Hospitality Management",
];

const DESIGNATIONS = [
  "Senior Lecturer & HOD",
  "Senior Lecturer",
  "Associate Professor",
  "Assistant Professor",
  "Lecturer",
  "Assistant Lecturer",
  "Teaching Associate / Lab Instructor",
];

export default function FacultyRegistrationPage() {
  const router = useRouter();

  // =========================================================================
  // 1. Faculty Personal & Professional Details
  // =========================================================================
  const [name, setName] = useState("");
  const [employeeId, setEmployeeId] = useState("");
  const [designation, setDesignation] = useState("Lecturer");
  const [department, setDepartment] = useState("Food Production");
  const [qualification, setQualification] = useState("");
  const [experience, setExperience] = useState("5 Years");
  const [specialization, setSpecialization] = useState("");
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);

  // =========================================================================
  // 2. Contact Details
  // =========================================================================
  const [email, setEmail] = useState("");
  const [mobile, setMobile] = useState("");
  const [officeLocation, setOfficeLocation] = useState("Academic Block A - Staff Room");

  // =========================================================================
  // 3. Subject Allocation
  // =========================================================================
  const [selectedSubjects, setSelectedSubjects] = useState<string[]>([
    "BHM111",
    "BHM211",
  ]);

  // =========================================================================
  // 4. Timetable & Weekly Hours
  // =========================================================================
  const [weeklyTheoryHours, setWeeklyTheoryHours] = useState<number>(4);
  const [weeklyPracticalHours, setWeeklyPracticalHours] = useState<number>(12);
  const [preferredShift, setPreferredShift] = useState("Morning Practicals & Afternoon Lectures");
  const [assignedRoom, setAssignedRoom] = useState("Basic Training Kitchen B (BTK-B)");

  // =========================================================================
  // 5. User Account Credentials
  // =========================================================================
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("IHMFaculty@2026");
  const [showPassword, setShowPassword] = useState(false);
  const [role, setRole] = useState<"FACULTY" | "DEPARTMENT_ADMIN">("FACULTY");
  const [requirePasswordChange, setRequirePasswordChange] = useState(true);
  const [enableBiometric, setEnableBiometric] = useState(true);

  // =========================================================================
  // 6. Account Status
  // =========================================================================
  const [status, setStatus] = useState<"Active" | "On Probation" | "On Leave" | "Inactive">("Active");
  const [joiningDate, setJoiningDate] = useState("2026-10-15");

  const [isSubmitting, setIsSubmitting] = useState(false);

  // Auto-generate employee ID, username and email when name changes
  const handleNameChange = (val: string) => {
    setName(val);
    const cleaned = val.trim().toLowerCase().replace(/[^a-z0-9]/g, ".");
    if (cleaned && !username) {
      setUsername(cleaned);
    }
    if (cleaned && !email) {
      setEmail(`${cleaned}@ihmkolkata.edu.in`);
    }
  };

  const handleGenerateEmployeeId = () => {
    const deptPrefix = department.slice(0, 2).toUpperCase();
    const randomNum = Math.floor(100 + Math.random() * 900);
    const generated = `EMP-${deptPrefix}${randomNum}`;
    setEmployeeId(generated);
    toast.success(`Generated Employee ID: ${generated}`);
  };

  const handleToggleSubject = (code: string) => {
    setSelectedSubjects((prev) =>
      prev.includes(code) ? prev.filter((c) => c !== code) : [...prev, code]
    );
  };

  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) => {
        setPhotoPreview(event.target?.result as string);
        toast.success("Faculty profile photograph loaded");
      };
      reader.readAsDataURL(file);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) {
      toast.error("Faculty Name is required");
      return;
    }
    if (!employeeId.trim()) {
      toast.error("Employee ID is required");
      return;
    }
    if (!email.trim()) {
      toast.error("Institutional Email is required");
      return;
    }
    if (!username.trim()) {
      toast.error("System Username is required");
      return;
    }

    setIsSubmitting(true);
    setTimeout(() => {
      setIsSubmitting(false);
      toast.success(
        `Faculty member ${name} (${employeeId}) registered successfully with ${selectedSubjects.length} allocated subjects.`
      );
      router.push("/admin/people/faculty/profiles");
    }, 600);
  };

  const handleReset = () => {
    setName("");
    setEmployeeId("");
    setDesignation("Lecturer");
    setDepartment("Food Production");
    setQualification("");
    setExperience("5 Years");
    setSpecialization("");
    setEmail("");
    setMobile("");
    setOfficeLocation("Academic Block A - Staff Room");
    setSelectedSubjects(["BHM111", "BHM211"]);
    setWeeklyTheoryHours(4);
    setWeeklyPracticalHours(12);
    setUsername("");
    setPassword("IHMFaculty@2026");
    setStatus("Active");
    setPhotoPreview(null);
    toast.info("Faculty registration form reset to defaults");
  };

  const getInitials = (n: string) => {
    if (!n.trim()) return "FC";
    return n
      .trim()
      .split(" ")
      .filter((p) => !["chef", "dr.", "prof.", "mr.", "ms.", "mrs."].includes(p.toLowerCase()))
      .map((part) => part[0])
      .join("")
      .toUpperCase()
      .slice(0, 2) || "FC";
  };

  const totalWeeklyHours = weeklyTheoryHours + weeklyPracticalHours;

  return (
    <div className="space-y-6 pb-12 font-sans bg-[#F8FAFC] min-h-screen">
      {/* 1. Header & Breadcrumb */}
      <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/faculty" className="hover:text-[#1769E8] hover:underline">
            Faculty Management
          </Link>
          <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
          <span className="text-[#071A4D] font-semibold">Faculty 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 font-heading text-[#071A4D] tracking-tight">
              Faculty Registration
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Register new academic faculty member with departmental affiliation, subject allocations, weekly timetable assignment, and portal user credentials.
            </p>
          </div>

          <div className="flex items-center gap-3">
            <Link
              href="/admin/people/faculty"
              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>Faculty Directory</span>
            </Link>
            <Link
              href="/admin/people/faculty/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"
            >
              <Users className="w-4 h-4 text-[#1769E8]" />
              <span>View Profiles</span>
            </Link>
          </div>
        </div>
      </div>

      {/* 2. Unified 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 & Professional Identity */}
          <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-heading font-bold text-base text-[#071A4D]">
                Faculty Personal &amp; Professional Identity
              </h2>
            </div>

            {/* Photo Upload & Initials Avatar Badge */}
            <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="Faculty Preview"
                    className="w-20 h-20 rounded-2xl object-cover border-2 border-[#1769E8] shadow-md ring-4 ring-blue-50"
                  />
                ) : (
                  <div className="w-20 h-20 rounded-2xl 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 font-heading">
                    {getInitials(name)}
                  </div>
                )}
                <label
                  htmlFor="faculty-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="faculty-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]">
                    Faculty Official Photograph &amp; ID Avatar
                  </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
                  </span>
                </div>
                <p className="text-[11px] text-[#64748B]">
                  Photograph is displayed on attendance marking consoles, timetable allocations, and student evaluation rosters.
                </p>
                <div className="flex items-center justify-center sm:justify-start gap-2 pt-1">
                  <label
                    htmlFor="faculty-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 Photo</span>
                  </label>
                  {photoPreview && (
                    <button
                      type="button"
                      onClick={() => setPhotoPreview(null)}
                      className="text-xs text-rose-600 hover:underline font-medium"
                    >
                      Remove
                    </button>
                  )}
                </div>
              </div>
            </div>

            {/* Faculty Name & Employee ID */}
            <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">
                  Faculty Name <span className="text-rose-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={name}
                  onChange={(e) => handleNameChange(e.target.value)}
                  placeholder="e.g. Chef Rajesh Sharma, Dr. Sunita Sen"
                  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">
                  Official name with academic title/honorific as recognized in NCHMCT records.
                </p>
              </div>

              <div>
                <div className="flex items-center justify-between mb-1.5">
                  <label className="text-xs font-bold text-[#334155] uppercase tracking-wider">
                    Employee ID <span className="text-rose-500">*</span>
                  </label>
                  <button
                    type="button"
                    onClick={handleGenerateEmployeeId}
                    className="text-[11px] font-semibold text-[#1769E8] hover:underline flex items-center gap-1 cursor-pointer"
                  >
                    <Sparkles className="w-3 h-3" />
                    <span>Auto Generate</span>
                  </button>
                </div>
                <div className="relative">
                  <Hash className="w-4 h-4 text-[#94A3B8] absolute left-3 top-1/2 -translate-y-1/2" />
                  <input
                    type="text"
                    required
                    value={employeeId}
                    onChange={(e) => setEmployeeId(e.target.value.toUpperCase())}
                    placeholder="e.g. EMP-FP106"
                    className="w-full pl-9 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-bold"
                  />
                </div>
                <p className="text-[11px] text-[#64748B] mt-1">
                  Institutional faculty payroll and biometric employee identifier.
                </p>
              </div>
            </div>

            {/* Designation & Department */}
            <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">
                  Designation <span className="text-rose-500">*</span>
                </label>
                <select
                  value={designation}
                  onChange={(e) => setDesignation(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"
                >
                  {DESIGNATIONS.map((desig) => (
                    <option key={desig}>{desig}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Department <span className="text-rose-500">*</span>
                </label>
                <select
                  value={department}
                  onChange={(e) => setDepartment(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"
                >
                  {DEPARTMENTS.map((dept) => (
                    <option key={dept}>{dept}</option>
                  ))}
                </select>
              </div>
            </div>

            {/* Qualification, Experience & Specialization */}
            <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">
                  Qualification <span className="text-rose-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={qualification}
                  onChange={(e) => setQualification(e.target.value)}
                  placeholder="e.g. M.Sc. Hospitality, Ph.D."
                  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"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Teaching Experience
                </label>
                <input
                  type="text"
                  value={experience}
                  onChange={(e) => setExperience(e.target.value)}
                  placeholder="e.g. 10 Years"
                  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"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Culinary / Academic Specialization
                </label>
                <input
                  type="text"
                  value={specialization}
                  onChange={(e) => setSpecialization(e.target.value)}
                  placeholder="e.g. French Cuisine, Bakery, PMS"
                  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"
                />
              </div>
            </div>
          </div>

          {/* SECTION 2: Contact Details */}
          <div className="space-y-5">
            <div className="flex items-center gap-2.5 pb-3.5 border-b border-[#E5EAF0]">
              <Mail className="w-5 h-5 text-[#1769E8]" />
              <h2 className="font-heading font-bold text-base text-[#071A4D]">
                Contact &amp; Campus Location
              </h2>
            </div>

            <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 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="faculty@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 Number <span className="text-rose-500">*</span></span>
                </label>
                <input
                  type="tel"
                  required
                  value={mobile}
                  onChange={(e) => setMobile(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>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider flex items-center gap-1.5">
                  <Building2 className="w-3.5 h-3.5 text-[#1769E8]" />
                  <span>Office / Cabin Location</span>
                </label>
                <input
                  type="text"
                  value={officeLocation}
                  onChange={(e) => setOfficeLocation(e.target.value)}
                  placeholder="e.g. Block A - Staff Room 204"
                  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"
                />
              </div>
            </div>
          </div>

          {/* SECTION 3: Subject Allocation */}
          <div className="space-y-4">
            <div className="flex items-center justify-between pb-3.5 border-b border-[#E5EAF0]">
              <div className="flex items-center gap-2.5">
                <BookOpen className="w-5 h-5 text-[#1769E8]" />
                <div>
                  <h2 className="font-heading font-bold text-base text-[#071A4D]">
                    Subject Allocation
                  </h2>
                  <p className="text-[11px] text-[#64748B]">
                    Select courses and curriculum subjects assigned to this faculty member for teaching and attendance recording.
                  </p>
                </div>
              </div>
              <span className="text-xs font-bold px-2.5 py-1 rounded-full bg-blue-50 text-[#1769E8] border border-blue-100">
                {selectedSubjects.length} Subjects Selected
              </span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              {AVAILABLE_SUBJECTS.map((subject) => {
                const isSelected = selectedSubjects.includes(subject.code);
                return (
                  <div
                    key={subject.code}
                    onClick={() => handleToggleSubject(subject.code)}
                    className={`p-3.5 rounded-xl border transition-all cursor-pointer flex items-center justify-between select-none ${
                      isSelected
                        ? "bg-blue-50/60 border-[#1769E8] shadow-xs"
                        : "bg-white border-[#E2E8F0] hover:border-slate-300 hover:bg-slate-50/50"
                    }`}
                  >
                    <div className="flex items-center gap-3">
                      <div
                        className={`w-5 h-5 rounded flex items-center justify-center transition-colors ${
                          isSelected
                            ? "bg-[#1769E8] text-white"
                            : "border border-slate-300 bg-white"
                        }`}
                      >
                        {isSelected && <CheckCircle2 className="w-3.5 h-3.5" />}
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="font-mono font-bold text-xs text-[#071A4D]">
                            {subject.code}
                          </span>
                          <span className="text-[10px] font-semibold px-1.5 py-0.2 rounded bg-slate-100 text-slate-600">
                            {subject.type}
                          </span>
                        </div>
                        <p className="text-xs font-medium text-slate-700 mt-0.5">
                          {subject.name}
                        </p>
                      </div>
                    </div>

                    <div className="text-right shrink-0">
                      <span className="text-[11px] font-bold text-slate-600 block">
                        {subject.hours} hrs/wk
                      </span>
                      <span className="text-[9.5px] text-slate-400 uppercase font-medium">
                        {subject.department}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* SECTION 4: Timetable & Weekly Teaching Schedule */}
          <div className="space-y-5">
            <div className="flex items-center gap-2.5 pb-3.5 border-b border-[#E5EAF0]">
              <Clock className="w-5 h-5 text-[#1769E8]" />
              <div>
                <h2 className="font-heading font-bold text-base text-[#071A4D]">
                  Timetable &amp; Teaching Schedule
                </h2>
                <p className="text-[11px] text-[#64748B]">
                  Assign teaching hours, target workload breakdown, and default kitchen/laboratory teaching facility.
                </p>
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Weekly Theory Hours
                </label>
                <input
                  type="number"
                  min="0"
                  max="30"
                  value={weeklyTheoryHours}
                  onChange={(e) => setWeeklyTheoryHours(Number(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 font-bold font-mono"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Weekly Practical Hours
                </label>
                <input
                  type="number"
                  min="0"
                  max="30"
                  value={weeklyPracticalHours}
                  onChange={(e) => setWeeklyPracticalHours(Number(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 font-bold font-mono"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Total Teaching Hours / Wk
                </label>
                <div className="px-3.5 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm font-bold font-mono text-[#071A4D] flex items-center justify-between">
                  <span>{totalWeeklyHours} Hours</span>
                  <span className={`text-[10px] px-2 py-0.5 rounded font-bold uppercase ${totalWeeklyHours >= 14 ? "bg-emerald-100 text-emerald-800" : "bg-amber-100 text-amber-800"}`}>
                    {totalWeeklyHours >= 14 ? "Full Load" : "Partial"}
                  </span>
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Default Assigned Lab / Room
                </label>
                <input
                  type="text"
                  value={assignedRoom}
                  onChange={(e) => setAssignedRoom(e.target.value)}
                  placeholder="e.g. BTK Kitchen Lab B"
                  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 font-medium"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                Timetable Slot &amp; Shift Preference
              </label>
              <select
                value={preferredShift}
                onChange={(e) => setPreferredShift(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 cursor-pointer font-medium"
              >
                <option>Morning Practicals &amp; Afternoon Lectures (09:00 AM – 05:00 PM)</option>
                <option>Afternoon Practicals &amp; Evening Review (12:00 PM – 06:00 PM)</option>
                <option>Theory Focused (Daily 10:00 AM – 02:00 PM)</option>
                <option>Full Day Intensive Laboratory Practical Rotation</option>
              </select>
            </div>
          </div>

          {/* SECTION 5: User Account Credentials */}
          <div className="space-y-5">
            <div className="flex items-center gap-2.5 pb-3.5 border-b border-[#E5EAF0]">
              <KeyRound className="w-5 h-5 text-[#1769E8]" />
              <div>
                <h2 className="font-heading font-bold text-base text-[#071A4D]">
                  User Account Credentials
                </h2>
                <p className="text-[11px] text-[#64748B]">
                  Provision institutional portal authentication credentials for web &amp; biometric terminal sign-in.
                </p>
              </div>
            </div>

            <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">
                  Portal Username <span className="text-rose-500">*</span>
                </label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 font-mono text-xs">@</span>
                  <input
                    type="text"
                    required
                    value={username}
                    onChange={(e) => setUsername(e.target.value.toLowerCase())}
                    placeholder="rajesh.sharma"
                    className="w-full pl-8 pr-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 font-mono font-bold"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Temporary Initial Password <span className="text-rose-500">*</span>
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? "text" : "password"}
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full pl-3.5 pr-10 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 font-mono"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer"
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1.5 uppercase tracking-wider">
                  Security Access Role
                </label>
                <select
                  value={role}
                  onChange={(e) => setRole(e.target.value as any)}
                  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 cursor-pointer font-medium"
                >
                  <option value="FACULTY">FACULTY (Teaching Staff &amp; Attendance Marker)</option>
                  <option value="DEPARTMENT_ADMIN">DEPARTMENT_ADMIN (Head of Department / HOD)</option>
                </select>
              </div>
            </div>

            <div className="flex flex-col sm:flex-row gap-4 pt-1">
              <label className="flex items-center gap-2 cursor-pointer select-none">
                <input
                  type="checkbox"
                  checked={requirePasswordChange}
                  onChange={(e) => setRequirePasswordChange(e.target.checked)}
                  className="rounded border-[#CBD5E1] text-[#1769E8] focus:ring-[#1769E8]"
                />
                <span className="text-xs font-medium text-slate-700">
                  Force password reset on first faculty sign-in
                </span>
              </label>

              <label className="flex items-center gap-2 cursor-pointer select-none">
                <input
                  type="checkbox"
                  checked={enableBiometric}
                  onChange={(e) => setEnableBiometric(e.target.checked)}
                  className="rounded border-[#CBD5E1] text-[#1769E8] focus:ring-[#1769E8]"
                />
                <span className="text-xs font-medium text-slate-700">
                  Allow biometric attendance turnstile login
                </span>
              </label>
            </div>
          </div>

          {/* SECTION 6: Account Status */}
          <div className="space-y-5">
            <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-heading font-bold text-base text-[#071A4D]">
                Account Status &amp; Effective Date
              </h2>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-[#334155] mb-2 uppercase tracking-wider">
                  Account Status <span className="text-rose-500">*</span>
                </label>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                  {(["Active", "On Probation", "On Leave", "Inactive"] as const).map((st) => (
                    <button
                      type="button"
                      key={st}
                      onClick={() => setStatus(st)}
                      className={`py-2 px-3 rounded-lg text-xs font-bold border transition-all text-center cursor-pointer ${
                        status === st
                          ? st === "Active"
                            ? "bg-emerald-600 text-white border-emerald-600 shadow-xs"
                            : st === "On Probation"
                            ? "bg-amber-500 text-white border-amber-500 shadow-xs"
                            : "bg-slate-800 text-white border-slate-800 shadow-xs"
                          : "bg-white text-slate-600 border-slate-200 hover:bg-slate-50"
                      }`}
                    >
                      {st}
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-[#334155] mb-2 uppercase tracking-wider">
                  Joining / Effective Appointment Date
                </label>
                <input
                  type="date"
                  value={joiningDate}
                  onChange={(e) => setJoiningDate(e.target.value)}
                  className="w-full px-3.5 py-2 bg-white border border-[#CBD5E1] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none font-medium"
                />
              </div>
            </div>
          </div>

          {/* Form Actions Footer */}
          <div className="pt-6 border-t border-[#E5EAF0] flex flex-col-reverse sm:flex-row items-center justify-between gap-3">
            <button
              type="button"
              onClick={handleReset}
              className="w-full sm:w-auto px-4 py-2.5 rounded-lg border border-[#CBD5E1] text-xs font-semibold text-[#475569] hover:bg-slate-50 transition-colors flex items-center justify-center gap-2 cursor-pointer shadow-2xs"
            >
              <RotateCcw className="w-3.5 h-3.5" />
              <span>Reset Form</span>
            </button>

            <div className="flex items-center gap-3 w-full sm:w-auto">
              <Link
                href="/admin/people/faculty"
                className="w-full sm:w-auto px-4 py-2.5 rounded-lg border border-[#CBD5E1] text-xs font-semibold text-[#475569] hover:bg-slate-50 transition-colors text-center cursor-pointer"
              >
                Cancel
              </Link>
              <button
                type="submit"
                disabled={isSubmitting}
                className="w-full sm:w-auto px-6 py-2.5 rounded-lg bg-[#1769E8] hover:bg-[#1257C7] text-white text-xs font-bold shadow-md shadow-[#1769E8]/20 transition-all flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50"
              >
                {isSubmitting ? (
                  <>
                    <RefreshCw className="w-4 h-4 animate-spin" />
                    <span>Registering...</span>
                  </>
                ) : (
                  <>
                    <Save className="w-4 h-4" />
                    <span>Register Faculty Member</span>
                  </>
                )}
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}
