"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  FileText,
  Plus,
  Edit2,
  Trash2,
  Eye,
  Search,
  RotateCcw,
  ChevronRight,
  FileSpreadsheet,
  Save,
  BookOpen,
  FlaskConical,
  X,
} from "lucide-react";
import { toast } from "sonner";
import { Subject, SubjectType } from "@/types/academic";

interface ExtendedSubject extends Subject {
  semesterName: string;
  department: string;
  status: "Active" | "Inactive";
}

const initialSubjectsList: ExtendedSubject[] = [
  {
    id: "sub-bhm201",
    semesterId: "sem-bhm-3",
    code: "BHM201",
    name: "Food Production Operations Practical",
    subjectType: "PRACTICAL",
    credits: 4,
    weeklyTeachingHours: 8,
    theoryContactHours: 0,
    practicalContactHours: 60,
    totalContactHours: 60,
    semesterName: "Semester III",
    department: "Food Production",
    status: "Active",
  },
  {
    id: "sub-bhm202",
    semesterId: "sem-bhm-3",
    code: "BHM202",
    name: "Food & Beverage Service Theory",
    subjectType: "THEORY",
    credits: 2,
    weeklyTeachingHours: 2,
    theoryContactHours: 30,
    practicalContactHours: 0,
    totalContactHours: 30,
    semesterName: "Semester III",
    department: "F&B Service",
    status: "Active",
  },
  {
    id: "sub-bhm203",
    semesterId: "sem-bhm-3",
    code: "BHM203",
    name: "Bakery & Confectionery Practical",
    subjectType: "PRACTICAL",
    credits: 3,
    weeklyTeachingHours: 4,
    theoryContactHours: 0,
    practicalContactHours: 40,
    totalContactHours: 40,
    semesterName: "Semester III",
    department: "Food Production",
    status: "Active",
  },
  {
    id: "sub-bhm204",
    semesterId: "sem-bhm-3",
    code: "BHM204",
    name: "Front Office Operations Theory",
    subjectType: "THEORY",
    credits: 2,
    weeklyTeachingHours: 2,
    theoryContactHours: 30,
    practicalContactHours: 0,
    totalContactHours: 30,
    semesterName: "Semester III",
    department: "Front Office",
    status: "Active",
  },
  {
    id: "sub-bhm205",
    semesterId: "sem-bhm-3",
    code: "BHM205",
    name: "Accommodation Operations Theory",
    subjectType: "THEORY",
    credits: 2,
    weeklyTeachingHours: 2,
    theoryContactHours: 30,
    practicalContactHours: 0,
    totalContactHours: 30,
    semesterName: "Semester III",
    department: "Housekeeping",
    status: "Active",
  },
  {
    id: "sub-bhm111",
    semesterId: "sem-bhm-1",
    code: "BHM111",
    name: "Foundation Course in Food Production I",
    subjectType: "THEORY",
    credits: 3,
    weeklyTeachingHours: 3,
    theoryContactHours: 45,
    practicalContactHours: 0,
    totalContactHours: 45,
    semesterName: "Semester I",
    department: "Food Production",
    status: "Active",
  },
  {
    id: "sub-bhm112",
    semesterId: "sem-bhm-1",
    code: "BHM112",
    name: "Foundation Course in F&B Service I",
    subjectType: "THEORY",
    credits: 3,
    weeklyTeachingHours: 3,
    theoryContactHours: 45,
    practicalContactHours: 0,
    totalContactHours: 45,
    semesterName: "Semester I",
    department: "F&B Service",
    status: "Active",
  },
];

export default function SubjectsPage() {
  const [subjects, setSubjects] = useState<ExtendedSubject[]>(initialSubjectsList);
  const [search, setSearch] = useState("");
  const [deptFilter, setDeptFilter] = useState("All Departments");
  const [typeFilter, setTypeFilter] = useState("All Types");
  const [semesterFilter, setSemesterFilter] = useState("All Semesters");
  const [pageSize, setPageSize] = useState("10 per page");

  // Selection
  const [selectedIds, setSelectedIds] = useState<string[]>([]);

  // Modal State
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalMode, setModalMode] = useState<"create" | "edit" | "view">("create");
  const [editingId, setEditingId] = useState<string | null>(null);
  const [viewingSubject, setViewingSubject] = useState<ExtendedSubject | null>(null);

  // Form State
  const [formCode, setFormCode] = useState("");
  const [formName, setFormName] = useState("");
  const [formDepartment, setFormDepartment] = useState("Food Production");
  const [formSemesterName, setFormSemesterName] = useState("Semester III");
  const [formSubjectType, setFormSubjectType] = useState<SubjectType>("THEORY");
  const [formCredits, setFormCredits] = useState<number>(3);
  const [formWeeklyTeachingHours, setFormWeeklyTeachingHours] = useState<number>(3);
  const [formTotalContactHours, setFormTotalContactHours] = useState<number>(45);
  const [formStatus, setFormStatus] = useState<"Active" | "Inactive">("Active");

  // Filtering
  const filtered = subjects.filter((sub) => {
    const matchesSearch =
      sub.code.toLowerCase().includes(search.toLowerCase()) ||
      sub.name.toLowerCase().includes(search.toLowerCase()) ||
      sub.department.toLowerCase().includes(search.toLowerCase());
    const matchesDept =
      deptFilter === "All Departments" || sub.department === deptFilter;
    const matchesType =
      typeFilter === "All Types" || sub.subjectType === typeFilter;
    const matchesSemester =
      semesterFilter === "All Semesters" || sub.semesterName === semesterFilter;
    return matchesSearch && matchesDept && matchesType && matchesSemester;
  });

  const handleResetFilters = () => {
    setSearch("");
    setDeptFilter("All Departments");
    setTypeFilter("All Types");
    setSemesterFilter("All Semesters");
  };

  const handleToggleSelectAll = () => {
    if (selectedIds.length === filtered.length) {
      setSelectedIds([]);
    } else {
      setSelectedIds(filtered.map((s) => s.id));
    }
  };

  const handleToggleSelectRow = (id: string) => {
    setSelectedIds((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
    );
  };

  const handleDelete = (id: string) => {
    const target = subjects.find((s) => s.id === id);
    if (target?.status === "Active") {
      toast.error("Cannot delete active subject currently scheduled for classes.");
      return;
    }
    setSubjects((prev) => prev.filter((s) => s.id !== id));
    toast.success("Subject deleted successfully.");
  };

  const openCreateModal = () => {
    setModalMode("create");
    setEditingId(null);
    setViewingSubject(null);
    setFormCode("");
    setFormName("");
    setFormDepartment("Food Production");
    setFormSemesterName("Semester III");
    setFormSubjectType("THEORY");
    setFormCredits(3);
    setFormWeeklyTeachingHours(3);
    setFormTotalContactHours(45);
    setFormStatus("Active");
    setIsModalOpen(true);
  };

  const openEditModal = (sub: ExtendedSubject) => {
    setModalMode("edit");
    setEditingId(sub.id);
    setViewingSubject(null);
    setFormCode(sub.code);
    setFormName(sub.name);
    setFormDepartment(sub.department);
    setFormSemesterName(sub.semesterName);
    setFormSubjectType(sub.subjectType);
    setFormCredits(sub.credits);
    setFormWeeklyTeachingHours(sub.weeklyTeachingHours);
    setFormTotalContactHours(sub.totalContactHours);
    setFormStatus(sub.status);
    setIsModalOpen(true);
  };

  const openViewModal = (sub: ExtendedSubject) => {
    setViewingSubject(sub);
    setModalMode("view");
    setIsModalOpen(true);
  };

  const handleSaveForm = (e: React.FormEvent) => {
    e.preventDefault();

    if (!formCode.trim() || !formName.trim()) {
      toast.error("Please enter subject code and title.");
      return;
    }

    if (editingId) {
      setSubjects((prev) =>
        prev.map((s) =>
          s.id === editingId
            ? {
                ...s,
                code: formCode.toUpperCase(),
                name: formName,
                department: formDepartment,
                semesterName: formSemesterName,
                subjectType: formSubjectType,
                credits: formCredits,
                weeklyTeachingHours: formWeeklyTeachingHours,
                totalContactHours: formTotalContactHours,
                status: formStatus,
              }
            : s
        )
      );
      toast.success("Subject updated successfully.");
    } else {
      const newSub: ExtendedSubject = {
        id: `sub-${Date.now()}`,
        semesterId: "sem-bhm-3",
        code: formCode.toUpperCase(),
        name: formName,
        department: formDepartment,
        semesterName: formSemesterName,
        subjectType: formSubjectType,
        credits: formCredits,
        weeklyTeachingHours: formWeeklyTeachingHours,
        theoryContactHours: formSubjectType === "THEORY" ? formTotalContactHours : 0,
        practicalContactHours: formSubjectType === "PRACTICAL" ? formTotalContactHours : 0,
        totalContactHours: formTotalContactHours,
        status: formStatus,
      };
      setSubjects((prev) => [newSub, ...prev]);
      toast.success("New subject added to catalog.");
    }

    setIsModalOpen(false);
  };

  return (
    <div className="space-y-5 font-sans">
      {/* ============================================================ */}
      {/* 1. TOP HEADER & BREADCRUMB                                   */}
      {/* ============================================================ */}
      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
        <div>
          <nav className="flex items-center gap-1.5 text-[13px] text-[#64748B] mb-1 font-medium">
            <Link href="/admin/dashboard" className="hover:text-[#1769E8] hover:underline">
              Home
            </Link>
            <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
            <span>Academic Management</span>
            <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
            <span className="text-[#071A4D] font-semibold">Subjects</span>
          </nav>

          <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
            Subjects
          </h1>
          <p className="text-[15px] text-[#64748B] mt-1 font-normal">
            Manage subject courses, theory/practical classification, contact hours, and credits.
          </p>
        </div>

        <div className="flex items-center gap-2.5 flex-wrap">
          <button
            onClick={() => toast.success("Exporting Subject Catalog...")}
            className="inline-flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-[#071A4D] bg-white border border-[#E5EAF0] rounded-lg hover:bg-slate-50 transition-colors shadow-2xs cursor-pointer"
          >
            <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
            <span>Export</span>
          </button>

          <button
            onClick={openCreateModal}
            className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-[#1769E8] hover:bg-[#1257C7] rounded-lg shadow-sm transition-colors cursor-pointer"
          >
            <Plus className="w-4 h-4" />
            <span>+ Add Subject</span>
          </button>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 2. FILTER AND SEARCH BAR                                     */}
      {/* ============================================================ */}
      <div className="p-4 rounded-xl bg-white border border-[#E5EAF0] shadow-xs flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-3">
        <div className="flex flex-wrap items-center gap-2.5 flex-1">
          {/* Department Filter */}
          <div className="flex flex-col">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider">
              Department
            </label>
            <select
              value={deptFilter}
              onChange={(e) => setDeptFilter(e.target.value)}
              className="h-9 px-3 rounded-lg border border-[#D8E0EA] bg-white text-xs font-medium text-[#334155] focus:outline-none focus:border-[#1769E8] cursor-pointer"
            >
              <option>All Departments</option>
              <option>Food Production</option>
              <option>F&B Service</option>
              <option>Front Office</option>
              <option>Housekeeping</option>
            </select>
          </div>

          {/* Type Filter */}
          <div className="flex flex-col">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider">
              Subject Type
            </label>
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
              className="h-9 px-3 rounded-lg border border-[#D8E0EA] bg-white text-xs font-medium text-[#334155] focus:outline-none focus:border-[#1769E8] cursor-pointer"
            >
              <option>All Types</option>
              <option>THEORY</option>
              <option>PRACTICAL</option>
            </select>
          </div>

          {/* Semester Filter */}
          <div className="flex flex-col">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider">
              Semester
            </label>
            <select
              value={semesterFilter}
              onChange={(e) => setSemesterFilter(e.target.value)}
              className="h-9 px-3 rounded-lg border border-[#D8E0EA] bg-white text-xs font-medium text-[#334155] focus:outline-none focus:border-[#1769E8] cursor-pointer"
            >
              <option>All Semesters</option>
              <option>Semester I</option>
              <option>Semester II</option>
              <option>Semester III</option>
              <option>Semester IV</option>
              <option>Semester V</option>
              <option>Semester VI</option>
            </select>
          </div>

          {/* Search Box */}
          <div className="flex flex-col flex-1 min-w-[220px]">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider opacity-0">
              Search
            </label>
            <div className="relative">
              <Search className="w-4 h-4 text-[#94A3B8] absolute left-3 top-1/2 -translate-y-1/2" />
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search by code, subject title, dept..."
                className="h-9 w-full rounded-lg border border-[#D8E0EA] bg-white pl-9 pr-3 text-xs text-[#334155] placeholder:text-[#94A3B8] focus:outline-none focus:border-[#1769E8]"
              />
            </div>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex items-end gap-2 shrink-0 pt-3 lg:pt-0">
          <button
            onClick={() => {}}
            className="h-9 px-4 rounded-lg bg-[#1769E8] hover:bg-[#1257C7] text-white text-xs font-semibold flex items-center gap-1.5 shadow-xs transition-colors cursor-pointer"
          >
            <Search className="w-3.5 h-3.5" />
            <span>Search</span>
          </button>

          <button
            onClick={handleResetFilters}
            className="h-9 px-4 rounded-lg border border-[#E5EAF0] hover:bg-slate-50 text-[#334155] text-xs font-semibold flex items-center gap-1.5 transition-colors shadow-2xs cursor-pointer"
          >
            <RotateCcw className="w-3.5 h-3.5 text-[#64748B]" />
            <span>Reset</span>
          </button>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 3. FULL WIDTH SUBJECTS TABLE - ALL DETAILS IN A LINE          */}
      {/* ============================================================ */}
      <div className="rounded-xl bg-white border border-[#E5EAF0] shadow-xs overflow-hidden">
        {/* Table Header Controls */}
        <div className="p-4 border-b border-[#E5EAF0] flex items-center justify-between">
          <div className="flex items-center gap-2">
            <FileText className="w-4 h-4 text-[#1769E8]" />
            <h2 className="text-sm font-bold font-heading text-[#071A4D]">
              Subjects Catalog ({filtered.length})
            </h2>
          </div>

          <select
            value={pageSize}
            onChange={(e) => setPageSize(e.target.value)}
            className="h-8 px-2.5 rounded-lg border border-[#D8E0EA] bg-white text-xs text-[#64748B] focus:outline-none focus:border-[#1769E8] cursor-pointer"
          >
            <option>10 per page</option>
            <option>25 per page</option>
            <option>50 per page</option>
          </select>
        </div>

        {/* Table Data */}
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs border-collapse">
            <thead>
              <tr className="bg-[#F8FAFC] border-b border-[#E5EAF0] text-[#64748B] uppercase tracking-wider font-bold text-[11px] whitespace-nowrap">
                <th className="py-3 px-3.5 text-center w-10">
                  <input
                    type="checkbox"
                    checked={selectedIds.length === filtered.length && filtered.length > 0}
                    onChange={handleToggleSelectAll}
                    className="rounded border-[#D8E0EA] text-[#1769E8] focus:ring-[#1769E8]"
                  />
                </th>
                <th className="py-3 px-2 text-center w-10">#</th>
                <th className="py-3 px-4">Subject Code</th>
                <th className="py-3 px-4">Subject Name</th>
                <th className="py-3 px-4">Department</th>
                <th className="py-3 px-4">Semester</th>
                <th className="py-3 px-4 text-center">Type</th>
                <th className="py-3 px-4 text-center">Credits</th>
                <th className="py-3 px-4 text-center">Weekly Hrs</th>
                <th className="py-3 px-4 text-center">Contact Hrs</th>
                <th className="py-3 px-4 text-center">Status</th>
                <th className="py-3 px-4 text-center">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0] text-[#334155]">
              {filtered.length === 0 ? (
                <tr>
                  <td colSpan={12} className="py-12 text-center text-slate-400">
                    No subjects match the filter criteria.
                  </td>
                </tr>
              ) : (
                filtered.map((sub, idx) => {
                  const isSelected = selectedIds.includes(sub.id);
                  return (
                    <tr
                      key={sub.id}
                      className={`hover:bg-[#F8FAFC] transition-colors whitespace-nowrap ${
                        isSelected ? "bg-blue-50/40" : ""
                      }`}
                    >
                      <td className="py-3.5 px-3.5 text-center">
                        <input
                          type="checkbox"
                          checked={isSelected}
                          onChange={() => handleToggleSelectRow(sub.id)}
                          className="rounded border-[#D8E0EA] text-[#1769E8] focus:ring-[#1769E8]"
                        />
                      </td>
                      <td className="py-3.5 px-2 text-center text-slate-400 font-medium">
                        {idx + 1}
                      </td>
                      <td className="py-3.5 px-4 font-bold text-[#071A4D]">
                        <span className="font-mono bg-slate-100 px-2 py-0.5 rounded text-[11px] text-[#071A4D]">
                          {sub.code}
                        </span>
                      </td>
                      <td className="py-3.5 px-4 font-semibold text-[#071A4D]">
                        {sub.name}
                      </td>
                      <td className="py-3.5 px-4 text-[#334155]">
                        <span className="inline-flex items-center px-2 py-0.5 rounded-md text-[11px] font-medium bg-slate-100 text-slate-700">
                          {sub.department}
                        </span>
                      </td>
                      <td className="py-3.5 px-4 text-[#475569]">
                        {sub.semesterName}
                      </td>
                      <td className="py-3.5 px-4 text-center">
                        {sub.subjectType === "THEORY" ? (
                          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-blue-50 text-[#1769E8]">
                            <BookOpen className="w-3 h-3" />
                            THEORY
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-purple-50 text-[#9333EA]">
                            <FlaskConical className="w-3 h-3" />
                            PRACTICAL
                          </span>
                        )}
                      </td>
                      <td className="py-3.5 px-4 text-center font-bold text-[#071A4D]">
                        {sub.credits}
                      </td>
                      <td className="py-3.5 px-4 text-center text-[#64748B]">
                        {sub.weeklyTeachingHours} hrs/wk
                      </td>
                      <td className="py-3.5 px-4 text-center text-[#64748B]">
                        {sub.totalContactHours} hrs
                      </td>
                      <td className="py-3.5 px-4 text-center">
                        {sub.status === "Active" ? (
                          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-[#DCFCE7] text-[#15803D]">
                            <span className="w-1.5 h-1.5 rounded-full bg-[#15803D]"></span>
                            Active
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-[#E2E8F0] text-[#475569]">
                            <span className="w-1.5 h-1.5 rounded-full bg-[#475569]"></span>
                            Inactive
                          </span>
                        )}
                      </td>
                      <td className="py-3.5 px-4 text-center">
                        <div className="flex items-center justify-center gap-1.5">
                          <button
                            onClick={() => openViewModal(sub)}
                            className="p-1.5 rounded-lg text-[#1769E8] hover:bg-blue-50 transition-colors"
                            title="View subject details"
                          >
                            <Eye className="w-4 h-4" />
                          </button>

                          <button
                            onClick={() => openEditModal(sub)}
                            className="p-1.5 rounded-lg text-[#1769E8] hover:bg-blue-50 transition-colors"
                            title="Edit subject"
                          >
                            <Edit2 className="w-4 h-4" />
                          </button>

                          <button
                            onClick={() => handleDelete(sub.id)}
                            className="p-1.5 rounded-lg text-[#DC2626] hover:bg-red-50 transition-colors"
                            title="Delete subject"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination Footer */}
        <div className="p-3.5 px-4 border-t border-[#E5EAF0] flex items-center justify-between text-xs text-[#64748B]">
          <div>
            Showing 1 to {filtered.length} of {subjects.length} subjects
          </div>
          <div className="flex items-center gap-1">
            <button
              disabled
              className="px-2.5 py-1 rounded border border-[#E5EAF0] text-slate-300 cursor-not-allowed"
            >
              &lt;
            </button>
            <button className="px-3 py-1 rounded bg-[#1769E8] text-white font-bold">
              1
            </button>
            <button
              disabled
              className="px-2.5 py-1 rounded border border-[#E5EAF0] text-slate-300 cursor-not-allowed"
            >
              &gt;
            </button>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 4. POPUP MODAL: CREATE / EDIT / VIEW SUBJECT                 */}
      {/* ============================================================ */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-xs p-4 animate-in fade-in duration-150">
          <div className="w-full max-w-lg bg-white rounded-2xl shadow-2xl border border-[#E5EAF0] overflow-hidden flex flex-col max-h-[90vh]">
            {/* Header */}
            <div className="px-6 py-4 border-b border-[#E5EAF0] flex items-center justify-between bg-slate-50/60">
              <div className="flex items-center gap-2.5">
                <div className="w-9 h-9 rounded-xl bg-blue-50 text-[#1769E8] flex items-center justify-center">
                  <FileText className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="font-heading font-bold text-base text-[#071A4D]">
                    {modalMode === "create" && "Add New Subject"}
                    {modalMode === "edit" && "Edit Subject"}
                    {modalMode === "view" && "Subject Details"}
                  </h3>
                  <p className="text-[12px] text-[#64748B]">
                    {modalMode === "create" && "Add a new syllabus subject to the curriculum."}
                    {modalMode === "edit" && "Update subject contact hours and credits."}
                    {modalMode === "view" && "Complete details of this syllabus subject."}
                  </p>
                </div>
              </div>
              <button
                onClick={() => setIsModalOpen(false)}
                className="w-8 h-8 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 flex items-center justify-center transition-colors cursor-pointer"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Content */}
            <div className="p-6 overflow-y-auto space-y-4">
              {modalMode === "view" && viewingSubject ? (
                <div className="space-y-4 text-xs">
                  <div className="grid grid-cols-2 gap-4 p-4 rounded-xl bg-slate-50 border border-slate-100">
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Subject Code</span>
                      <span className="text-sm font-bold font-mono text-[#071A4D]">{viewingSubject.code}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Type</span>
                      <span className="text-sm font-semibold text-[#071A4D]">{viewingSubject.subjectType}</span>
                    </div>
                    <div className="col-span-2">
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Subject Name</span>
                      <span className="text-sm font-bold text-[#071A4D]">{viewingSubject.name}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Department</span>
                      <span className="text-xs font-medium text-[#334155]">{viewingSubject.department}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Semester</span>
                      <span className="text-xs font-medium text-[#334155]">{viewingSubject.semesterName}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Credits</span>
                      <span className="text-xs font-bold text-[#071A4D]">{viewingSubject.credits} Credits</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Weekly Teaching</span>
                      <span className="text-xs font-medium text-[#334155]">{viewingSubject.weeklyTeachingHours} Hours</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Total Contact Hours</span>
                      <span className="text-xs font-medium text-[#334155]">{viewingSubject.totalContactHours} Hours</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Status</span>
                      <span className={`inline-block mt-0.5 px-2 py-0.5 rounded-full font-semibold text-[10px] ${
                        viewingSubject.status === "Active"
                          ? "bg-emerald-100 text-emerald-700"
                          : "bg-slate-200 text-slate-700"
                      }`}>
                        {viewingSubject.status}
                      </span>
                    </div>
                  </div>
                </div>
              ) : (
                <form id="subject-form" onSubmit={handleSaveForm} className="space-y-4">
                  {/* Code & Name */}
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Code <span className="text-[#DC2626]">*</span>
                      </label>
                      <input
                        type="text"
                        required
                        value={formCode}
                        onChange={(e) => setFormCode(e.target.value)}
                        placeholder="e.g. BHM201"
                        className="h-10 w-full px-3 text-xs uppercase font-mono rounded-lg border border-[#D8E0EA] bg-white text-[#334155] placeholder:text-[#94A3B8] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                      />
                    </div>
                    <div className="sm:col-span-2">
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Subject Title <span className="text-[#DC2626]">*</span>
                      </label>
                      <input
                        type="text"
                        required
                        value={formName}
                        onChange={(e) => setFormName(e.target.value)}
                        placeholder="e.g. Food Production Operations Practical"
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] placeholder:text-[#94A3B8] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                      />
                    </div>
                  </div>

                  {/* Department & Semester */}
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Department <span className="text-[#DC2626]">*</span>
                      </label>
                      <select
                        value={formDepartment}
                        onChange={(e) => setFormDepartment(e.target.value)}
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20 cursor-pointer"
                      >
                        <option value="Food Production">Food Production</option>
                        <option value="F&B Service">F&B Service</option>
                        <option value="Front Office">Front Office</option>
                        <option value="Housekeeping">Housekeeping</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Semester <span className="text-[#DC2626]">*</span>
                      </label>
                      <select
                        value={formSemesterName}
                        onChange={(e) => setFormSemesterName(e.target.value)}
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20 cursor-pointer"
                      >
                        <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>

                  {/* Subject Type */}
                  <div>
                    <label className="block text-xs font-bold text-[#334155] mb-1">
                      Subject Type
                    </label>
                    <div className="flex items-center gap-5 text-xs pt-1">
                      <label className="flex items-center gap-1.5 cursor-pointer text-[#334155]">
                        <input
                          type="radio"
                          name="subType"
                          checked={formSubjectType === "THEORY"}
                          onChange={() => setFormSubjectType("THEORY")}
                          className="text-[#1769E8] focus:ring-[#1769E8]"
                        />
                        <span className="font-medium">Theory Class</span>
                      </label>

                      <label className="flex items-center gap-1.5 cursor-pointer text-[#334155]">
                        <input
                          type="radio"
                          name="subType"
                          checked={formSubjectType === "PRACTICAL"}
                          onChange={() => setFormSubjectType("PRACTICAL")}
                          className="text-[#1769E8] focus:ring-[#1769E8]"
                        />
                        <span className="font-medium">Practical Lab / Kitchen</span>
                      </label>
                    </div>
                  </div>

                  {/* Credits & Hours */}
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Credits
                      </label>
                      <input
                        type="number"
                        min="1"
                        max="10"
                        value={formCredits}
                        onChange={(e) => setFormCredits(Number(e.target.value))}
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Weekly Hrs
                      </label>
                      <input
                        type="number"
                        min="1"
                        max="20"
                        value={formWeeklyTeachingHours}
                        onChange={(e) => setFormWeeklyTeachingHours(Number(e.target.value))}
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Total Hrs
                      </label>
                      <input
                        type="number"
                        min="10"
                        max="200"
                        value={formTotalContactHours}
                        onChange={(e) => setFormTotalContactHours(Number(e.target.value))}
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                      />
                    </div>
                  </div>

                  {/* Status */}
                  <div>
                    <label className="block text-xs font-bold text-[#334155] mb-2">
                      Status
                    </label>
                    <div className="flex items-center gap-5 text-xs">
                      <label className="flex items-center gap-1.5 cursor-pointer text-[#334155]">
                        <input
                          type="radio"
                          name="subjectStatus"
                          checked={formStatus === "Active"}
                          onChange={() => setFormStatus("Active")}
                          className="text-[#1769E8] focus:ring-[#1769E8]"
                        />
                        <span className="font-medium">Active</span>
                      </label>

                      <label className="flex items-center gap-1.5 cursor-pointer text-[#334155]">
                        <input
                          type="radio"
                          name="subjectStatus"
                          checked={formStatus === "Inactive"}
                          onChange={() => setFormStatus("Inactive")}
                          className="text-[#1769E8] focus:ring-[#1769E8]"
                        />
                        <span className="font-medium">Inactive</span>
                      </label>
                    </div>
                  </div>
                </form>
              )}
            </div>

            {/* Footer */}
            <div className="px-6 py-3.5 border-t border-[#E5EAF0] flex items-center justify-end gap-2.5 bg-slate-50/50">
              <button
                type="button"
                onClick={() => setIsModalOpen(false)}
                className="px-4 py-2 text-xs font-semibold text-[#64748B] bg-white hover:bg-slate-100 border border-[#E5EAF0] rounded-lg transition-colors cursor-pointer"
              >
                {modalMode === "view" ? "Close" : "Cancel"}
              </button>

              {modalMode !== "view" && (
                <button
                  type="submit"
                  form="subject-form"
                  className="px-5 py-2 text-xs font-bold text-white bg-[#1769E8] hover:bg-[#1257C7] rounded-lg transition-colors flex items-center gap-1.5 shadow-xs cursor-pointer"
                >
                  <Save className="w-3.5 h-3.5" />
                  <span>{modalMode === "create" ? "Add Subject" : "Save Changes"}</span>
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
