"use client";

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

interface CourseItem {
  id: string;
  code: string;
  name: string;
  type: "Degree" | "Postgraduate" | "Diploma" | "Certificate" | "Advanced" | "Other";
  program: string;
  duration: string;
  status: "Active" | "Inactive";
  description?: string;
}

const initialCoursesList: CourseItem[] = [
  {
    id: "c-1",
    code: "BHM",
    name: "Bachelor of Hotel Management",
    type: "Degree",
    program: "BHM",
    duration: "4 Years",
    status: "Active",
    description: "Flagship 4-year undergraduate professional hospitality program.",
  },
  {
    id: "c-2",
    code: "MHM",
    name: "Master of Hotel Management",
    type: "Postgraduate",
    program: "MHM",
    duration: "2 Years",
    status: "Active",
    description: "Advanced master degree in institutional hospitality administration.",
  },
  {
    id: "c-3",
    code: "DCHM",
    name: "Diploma in Culinary Arts",
    type: "Diploma",
    program: "DCHM",
    duration: "1 Year",
    status: "Active",
    description: "Specialized diploma focusing on commercial culinary kitchen techniques.",
  },
  {
    id: "c-4",
    code: "DFB",
    name: "Diploma in Food & Beverage",
    type: "Diploma",
    program: "DFB",
    duration: "1 Year",
    status: "Active",
    description: "Intensive training in restaurant and beverage operations.",
  },
  {
    id: "c-5",
    code: "DHS",
    name: "Diploma in Housekeeping",
    type: "Diploma",
    program: "DHS",
    duration: "1 Year",
    status: "Active",
    description: "Professional hospitality housekeeping and facility maintenance.",
  },
  {
    id: "c-6",
    code: "DTT",
    name: "Diploma in Travel & Tourism",
    type: "Diploma",
    program: "DTT",
    duration: "1 Year",
    status: "Active",
    description: "Tourism management, travel regulations, and destination logistics.",
  },
  {
    id: "c-7",
    code: "CSH",
    name: "Certificate in Hospitality",
    type: "Certificate",
    program: "CSH",
    duration: "6 Months",
    status: "Active",
    description: "Short term foundational hospitality skills certificate.",
  },
  {
    id: "c-8",
    code: "CA",
    name: "Certificate in Culinary Arts",
    type: "Certificate",
    program: "CA",
    duration: "6 Months",
    status: "Inactive",
    description: "Foundation culinary certificate program.",
  },
  {
    id: "c-9",
    code: "BAK",
    name: "Certificate in Bakery & Patisserie",
    type: "Certificate",
    program: "BAK",
    duration: "6 Months",
    status: "Active",
    description: "Classical Viennoiserie, confectionery, and artisan bread craft.",
  },
  {
    id: "c-10",
    code: "FD",
    name: "Food Production",
    type: "Certificate",
    program: "FD",
    duration: "6 Months",
    status: "Active",
    description: "Foundational commercial kitchen apprentice course.",
  },
];

export default function CoursesPage() {
  const [courses, setCourses] = useState<CourseItem[]>(initialCoursesList);
  const [search, setSearch] = useState("");
  const [programFilter, setProgramFilter] = useState("All Programs");
  const [typeFilter, setTypeFilter] = useState("All Types");
  const [statusFilter, setStatusFilter] = useState("All Status");
  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 [viewingCourse, setViewingCourse] = useState<CourseItem | null>(null);

  // Form State
  const [formCode, setFormCode] = useState("");
  const [formName, setFormName] = useState("");
  const [formType, setFormType] = useState<CourseItem["type"]>("Degree");
  const [formProgram, setFormProgram] = useState("BHM");
  const [formDurationValue, setFormDurationValue] = useState("3");
  const [formDurationUnit, setFormDurationUnit] = useState("Years");
  const [formDescription, setFormDescription] = useState("");
  const [formStatus, setFormStatus] = useState<"Active" | "Inactive">("Active");

  // Filtering
  const filtered = courses.filter((c) => {
    const matchesSearch =
      c.code.toLowerCase().includes(search.toLowerCase()) ||
      c.name.toLowerCase().includes(search.toLowerCase()) ||
      c.program.toLowerCase().includes(search.toLowerCase());
    const matchesProgram =
      programFilter === "All Programs" || c.program === programFilter;
    const matchesType = typeFilter === "All Types" || c.type === typeFilter;
    const matchesStatus =
      statusFilter === "All Status" || c.status === statusFilter;
    return matchesSearch && matchesProgram && matchesType && matchesStatus;
  });

  const handleResetFilters = () => {
    setSearch("");
    setProgramFilter("All Programs");
    setTypeFilter("All Types");
    setStatusFilter("All Status");
  };

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

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

  const handleDelete = (id: string) => {
    const target = courses.find((c) => c.id === id);
    if (target?.status === "Active") {
      toast.error("Cannot delete active course with active enrolled batches.");
      return;
    }
    setCourses((prev) => prev.filter((c) => c.id !== id));
    toast.success("Course deleted successfully.");
  };

  const openCreateModal = () => {
    setModalMode("create");
    setEditingId(null);
    setViewingCourse(null);
    setFormCode("");
    setFormName("");
    setFormType("Degree");
    setFormProgram("BHM");
    setFormDurationValue("3");
    setFormDurationUnit("Years");
    setFormDescription("");
    setFormStatus("Active");
    setIsModalOpen(true);
  };

  const openEditModal = (c: CourseItem) => {
    setModalMode("edit");
    setEditingId(c.id);
    setViewingCourse(null);
    setFormCode(c.code);
    setFormName(c.name);
    setFormType(c.type);
    setFormProgram(c.program);
    const durParts = c.duration.split(" ");
    setFormDurationValue(durParts[0] || "1");
    setFormDurationUnit(durParts[1] || "Years");
    setFormDescription(c.description || "");
    setFormStatus(c.status);
    setIsModalOpen(true);
  };

  const openViewModal = (c: CourseItem) => {
    setViewingCourse(c);
    setModalMode("view");
    setIsModalOpen(true);
  };

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

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

    const duration = `${formDurationValue} ${formDurationUnit}`;

    if (editingId) {
      setCourses((prev) =>
        prev.map((c) =>
          c.id === editingId
            ? {
                ...c,
                code: formCode.toUpperCase(),
                name: formName,
                type: formType,
                program: formProgram,
                duration,
                description: formDescription,
                status: formStatus,
              }
            : c
        )
      );
      toast.success("Course updated successfully.");
    } else {
      const newCourse: CourseItem = {
        id: `c-${Date.now()}`,
        code: formCode.toUpperCase(),
        name: formName,
        type: formType,
        program: formProgram,
        duration,
        description: formDescription,
        status: formStatus,
      };
      setCourses((prev) => [newCourse, ...prev]);
      toast.success("New course created successfully.");
    }

    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">Courses</span>
          </nav>

          <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
            Courses
          </h1>
          <p className="text-[15px] text-[#64748B] mt-1 font-normal">
            Manage degree, diploma, certificate courses and academic curriculum structures.
          </p>
        </div>

        <div className="flex items-center gap-2.5 flex-wrap">
          <button
            onClick={() => toast.success("Exporting Course Catalog to CSV...")}
            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={() => toast.success("Generating courses syllabus summary...")}
            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"
          >
            <FileText className="w-4 h-4 text-[#9333EA]" />
            <span>Generate Report</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 Course</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">
          {/* Program Dropdown */}
          <div className="flex flex-col">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider">
              Program
            </label>
            <select
              value={programFilter}
              onChange={(e) => setProgramFilter(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 Programs</option>
              <option>BHM</option>
              <option>MHM</option>
              <option>DCHM</option>
              <option>DFB</option>
              <option>DHS</option>
              <option>DTT</option>
              <option>CSH</option>
              <option>CA</option>
              <option>BAK</option>
              <option>FD</option>
            </select>
          </div>

          {/* Type Dropdown */}
          <div className="flex flex-col">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider">
              Course 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>Degree</option>
              <option>Postgraduate</option>
              <option>Diploma</option>
              <option>Certificate</option>
            </select>
          </div>

          {/* Status Dropdown */}
          <div className="flex flex-col">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider">
              Status
            </label>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(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 Status</option>
              <option>Active</option>
              <option>Inactive</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, course name, program..."
                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>

        {/* 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 COURSES 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">
            <BookOpen className="w-4 h-4 text-[#1769E8]" />
            <h2 className="text-sm font-bold font-heading text-[#071A4D]">
              Courses 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">Course Code</th>
                <th className="py-3 px-4">Course Name</th>
                <th className="py-3 px-4">Program</th>
                <th className="py-3 px-4">Type</th>
                <th className="py-3 px-4">Duration</th>
                <th className="py-3 px-4">Description</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={10} className="py-12 text-center text-slate-400">
                    No courses match the specified filters.
                  </td>
                </tr>
              ) : (
                filtered.map((c, idx) => {
                  const isSelected = selectedIds.includes(c.id);
                  return (
                    <tr
                      key={c.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(c.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]">
                          {c.code}
                        </span>
                      </td>
                      <td className="py-3.5 px-4 font-semibold text-[#071A4D]">
                        {c.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-blue-50 text-[#1769E8]">
                          {c.program}
                        </span>
                      </td>
                      <td className="py-3.5 px-4 text-[#475569]">
                        {c.type}
                      </td>
                      <td className="py-3.5 px-4 text-[#64748B]">
                        {c.duration}
                      </td>
                      <td className="py-3.5 px-4 text-[#64748B] max-w-xs truncate">
                        {c.description || "—"}
                      </td>
                      <td className="py-3.5 px-4 text-center">
                        {c.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(c)}
                            className="p-1.5 rounded-lg text-[#1769E8] hover:bg-blue-50 transition-colors"
                            title="View course details"
                          >
                            <Eye className="w-4 h-4" />
                          </button>

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

                          <button
                            onClick={() => handleDelete(c.id)}
                            className="p-1.5 rounded-lg text-[#DC2626] hover:bg-red-50 transition-colors"
                            title="Delete course"
                          >
                            <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 {courses.length} courses
          </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 COURSE                  */}
      {/* ============================================================ */}
      {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">
                  <BookOpen className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="font-heading font-bold text-base text-[#071A4D]">
                    {modalMode === "create" && "Add New Course"}
                    {modalMode === "edit" && "Edit Course"}
                    {modalMode === "view" && "Course Overview"}
                  </h3>
                  <p className="text-[12px] text-[#64748B]">
                    {modalMode === "create" && "Fill out the fields below to register a new course."}
                    {modalMode === "edit" && "Update course details and duration."}
                    {modalMode === "view" && "Complete information about this course."}
                  </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" && viewingCourse ? (
                <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">Course Code</span>
                      <span className="text-sm font-bold font-mono text-[#071A4D]">{viewingCourse.code}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Course Type</span>
                      <span className="text-sm font-semibold text-[#071A4D]">{viewingCourse.type}</span>
                    </div>
                    <div className="col-span-2">
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Course Name</span>
                      <span className="text-sm font-bold text-[#071A4D]">{viewingCourse.name}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Program</span>
                      <span className="text-xs font-medium text-[#334155]">{viewingCourse.program}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Duration</span>
                      <span className="text-xs font-medium text-[#334155]">{viewingCourse.duration}</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] ${
                        viewingCourse.status === "Active"
                          ? "bg-emerald-100 text-emerald-700"
                          : "bg-slate-200 text-slate-700"
                      }`}>
                        {viewingCourse.status}
                      </span>
                    </div>
                  </div>

                  <div>
                    <span className="text-[10px] uppercase font-bold text-[#64748B] block mb-1">Description</span>
                    <p className="text-xs text-[#334155] leading-relaxed p-3 rounded-lg border border-slate-100 bg-white">
                      {viewingCourse.description || "No description provided."}
                    </p>
                  </div>
                </div>
              ) : (
                <form id="course-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. BHM"
                        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">
                        Course Name <span className="text-[#DC2626]">*</span>
                      </label>
                      <input
                        type="text"
                        required
                        value={formName}
                        onChange={(e) => setFormName(e.target.value)}
                        placeholder="e.g. Bachelor of Hotel Management"
                        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>

                  {/* Program & Type */}
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Program Code
                      </label>
                      <input
                        type="text"
                        value={formProgram}
                        onChange={(e) => setFormProgram(e.target.value)}
                        placeholder="e.g. BHM"
                        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">
                        Course Type
                      </label>
                      <select
                        value={formType}
                        onChange={(e) => setFormType(e.target.value as CourseItem["type"])}
                        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="Degree">Degree</option>
                        <option value="Postgraduate">Postgraduate</option>
                        <option value="Diploma">Diploma</option>
                        <option value="Certificate">Certificate</option>
                        <option value="Advanced">Advanced</option>
                      </select>
                    </div>
                  </div>

                  {/* Duration */}
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Duration Value
                      </label>
                      <input
                        type="number"
                        min="1"
                        max="10"
                        value={formDurationValue}
                        onChange={(e) => setFormDurationValue(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">
                        Duration Unit
                      </label>
                      <select
                        value={formDurationUnit}
                        onChange={(e) => setFormDurationUnit(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="Years">Years</option>
                        <option value="Months">Months</option>
                        <option value="Semesters">Semesters</option>
                        <option value="Weeks">Weeks</option>
                      </select>
                    </div>
                  </div>

                  {/* Description */}
                  <div>
                    <label className="block text-xs font-bold text-[#334155] mb-1">
                      Description
                    </label>
                    <textarea
                      rows={2}
                      value={formDescription}
                      onChange={(e) => setFormDescription(e.target.value)}
                      placeholder="Enter course curriculum overview or description..."
                      maxLength={500}
                      className="w-full p-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 resize-none"
                    />
                  </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="courseStatus"
                          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="courseStatus"
                          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="course-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" ? "Create Course" : "Save Changes"}</span>
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
