"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  GraduationCap,
  BookOpen,
  Plus,
  Search,
  Filter,
  CheckCircle2,
  ChevronRight,
  Clock,
  Award,
  Layers,
  X,
  Sparkles,
} from "lucide-react";
import { toast } from "sonner";

interface CourseItem {
  id: string;
  code: string;
  name: string;
  level: "UG" | "PG" | "DIPLOMA" | "CERTIFICATE";
  duration: string;
  totalSemesters: number;
  totalCredits: number;
  totalStudents: number;
  deptLead: string;
  status: "ACTIVE" | "INACTIVE";
}

export default function DeptAdminCoursesPage() {
  const [courses, setCourses] = useState<CourseItem[]>([
    {
      id: "c_bhm",
      code: "B.Sc. H&HA",
      name: "B.Sc. in Hospitality & Hotel Administration",
      level: "UG",
      duration: "3 Years",
      totalSemesters: 6,
      totalCredits: 140,
      totalStudents: 280,
      deptLead: "Chef Rajesh Sharma",
      status: "ACTIVE",
    },
    {
      id: "c_mha",
      code: "M.Sc. HA",
      name: "M.Sc. in Hospitality Administration",
      level: "PG",
      duration: "2 Years",
      totalSemesters: 4,
      totalCredits: 80,
      totalStudents: 42,
      deptLead: "Dr. Sunita Sharma",
      status: "ACTIVE",
    },
    {
      id: "c_dfp",
      code: "DFP",
      name: "Diploma in Food Production & Culinary Arts",
      level: "DIPLOMA",
      duration: "1.5 Years",
      totalSemesters: 3,
      totalCredits: 45,
      totalStudents: 38,
      deptLead: "Chef Anirban Roy",
      status: "ACTIVE",
    },
    {
      id: "c_cbc",
      code: "CBC",
      name: "Certificate in Bakery & Confectionery",
      level: "CERTIFICATE",
      duration: "1 Year",
      totalSemesters: 2,
      totalCredits: 30,
      totalStudents: 24,
      deptLead: "Chef Meenakshi Iyer",
      status: "ACTIVE",
    },
  ]);

  const [search, setSearch] = useState("");
  const [levelFilter, setLevelFilter] = useState("ALL");
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [formCode, setFormCode] = useState("");
  const [formName, setFormName] = useState("");
  const [formLevel, setFormLevel] = useState<"UG" | "PG" | "DIPLOMA" | "CERTIFICATE">("UG");
  const [formDuration, setFormDuration] = useState("3 Years");
  const [formSemesters, setFormSemesters] = useState(6);
  const [formCredits, setFormCredits] = useState(120);

  const filteredCourses = courses.filter((c) => {
    const matchesLevel = levelFilter === "ALL" || c.level === levelFilter;
    const matchesSearch =
      c.name.toLowerCase().includes(search.toLowerCase()) ||
      c.code.toLowerCase().includes(search.toLowerCase());
    return matchesLevel && matchesSearch;
  });

  const handleAddCourse = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formCode.trim() || !formName.trim()) {
      toast.error("Please provide course code and title");
      return;
    }

    const newCourse: CourseItem = {
      id: `c_${Date.now()}`,
      code: formCode,
      name: formName,
      level: formLevel,
      duration: formDuration,
      totalSemesters: Number(formSemesters),
      totalCredits: Number(formCredits),
      totalStudents: 0,
      deptLead: "Chef Rajesh Sharma",
      status: "ACTIVE",
    };

    setCourses([...courses, newCourse]);
    setIsModalOpen(false);
    setFormCode("");
    setFormName("");
    toast.success(`Course added: ${newCourse.code}`);
  };

  return (
    <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 text-xs font-semibold text-slate-500 mb-1">
            <Link href="/dept-admin/dashboard" className="hover:text-[#1769E8]">
              Dashboard
            </Link>
            <ChevronRight className="w-3.5 h-3.5" />
            <span className="text-[#071A4D] font-bold">Course Management</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-black text-[#071A4D] tracking-tight">
            Department Course Management
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Academic programs, degrees, curricula, and credit requirements for the department
          </p>
        </div>

        <button
          onClick={() => setIsModalOpen(true)}
          className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg bg-[#C8A45D] hover:bg-[#B38F48] text-slate-950 font-bold text-xs shadow-sm transition-all"
        >
          <Plus className="w-4 h-4" />
          <span>Add New Course</span>
        </button>
      </div>

      {/* Filter and Search */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-3 bg-white p-3.5 rounded-xl border border-slate-200 shadow-xs">
        <div className="relative w-full sm:w-72">
          <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search programs by name or code..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-9 pr-3 py-1.5 text-xs rounded-lg border border-slate-200 focus:outline-hidden focus:border-[#C8A45D]"
          />
        </div>

        <div className="flex items-center gap-2 w-full sm:w-auto overflow-x-auto">
          <span className="text-xs font-semibold text-slate-500 shrink-0">Level:</span>
          {["ALL", "UG", "PG", "DIPLOMA", "CERTIFICATE"].map((lvl) => (
            <button
              key={lvl}
              onClick={() => setLevelFilter(lvl)}
              className={`px-3 py-1 rounded-lg text-xs font-bold transition-colors whitespace-nowrap ${
                levelFilter === lvl
                  ? "bg-[#081A2E] text-white"
                  : "bg-slate-100 text-slate-600 hover:bg-slate-200"
              }`}
            >
              {lvl}
            </button>
          ))}
        </div>
      </div>

      {/* Course Cards Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
        {filteredCourses.map((c) => (
          <div
            key={c.id}
            className="p-5 rounded-xl bg-white border border-slate-200 shadow-xs hover:shadow-md transition-all flex flex-col justify-between"
          >
            <div>
              <div className="flex items-start justify-between gap-3 mb-2">
                <div>
                  <span className="text-[10px] font-bold px-2.5 py-0.5 rounded-full bg-amber-50 text-[#785E2F] border border-amber-200">
                    {c.level} Degree Program
                  </span>
                  <h3 className="text-base font-bold text-[#071A4D] mt-1.5">{c.name}</h3>
                </div>
                <span className="text-xs font-mono font-bold text-[#081A2E] bg-slate-100 px-2 py-1 rounded-md">
                  {c.code}
                </span>
              </div>

              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 py-3 border-y border-slate-100 text-xs mt-3">
                <div>
                  <span className="text-[10px] text-slate-400 block uppercase font-semibold">Duration</span>
                  <span className="font-bold text-slate-800">{c.duration}</span>
                </div>
                <div>
                  <span className="text-[10px] text-slate-400 block uppercase font-semibold">Semesters</span>
                  <span className="font-bold text-slate-800">{c.totalSemesters} Semesters</span>
                </div>
                <div>
                  <span className="text-[10px] text-slate-400 block uppercase font-semibold">Credits</span>
                  <span className="font-bold text-slate-800">{c.totalCredits} Credits</span>
                </div>
              </div>
            </div>

            <div className="pt-3 flex items-center justify-between text-xs mt-3">
              <div className="text-slate-500">
                Department Lead: <strong className="text-slate-700">{c.deptLead}</strong>
              </div>
              <div className="font-bold text-[#071A4D] bg-blue-50 text-blue-700 px-2.5 py-1 rounded-lg">
                {c.totalStudents} Students
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Add Course Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl max-w-lg w-full p-6 shadow-2xl border border-slate-200 animate-in fade-in zoom-in-95 duration-150">
            <div className="flex items-center justify-between pb-3 border-b border-slate-100">
              <h3 className="font-bold text-base text-[#071A4D]">Add Department Course</h3>
              <button
                onClick={() => setIsModalOpen(false)}
                className="p-1 rounded-lg text-slate-400 hover:text-slate-700"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleAddCourse} className="space-y-4 pt-4 text-xs">
              <div>
                <label className="font-bold text-slate-800 block mb-1">Course Title *</label>
                <input
                  type="text"
                  placeholder="e.g. Diploma in Bakery & Pastry Arts"
                  value={formName}
                  onChange={(e) => setFormName(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:border-[#C8A45D] focus:outline-hidden"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Short Code *</label>
                  <input
                    type="text"
                    placeholder="e.g. DBPA"
                    value={formCode}
                    onChange={(e) => setFormCode(e.target.value)}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:border-[#C8A45D] focus:outline-hidden"
                    required
                  />
                </div>
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Degree Level</label>
                  <select
                    value={formLevel}
                    onChange={(e) => setFormLevel(e.target.value as any)}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:border-[#C8A45D] focus:outline-hidden"
                  >
                    <option value="UG">Undergraduate (UG)</option>
                    <option value="PG">Postgraduate (PG)</option>
                    <option value="DIPLOMA">Diploma</option>
                    <option value="CERTIFICATE">Certificate</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Duration</label>
                  <input
                    type="text"
                    placeholder="1.5 Years"
                    value={formDuration}
                    onChange={(e) => setFormDuration(e.target.value)}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:border-[#C8A45D] focus:outline-hidden"
                  />
                </div>
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Semesters</label>
                  <input
                    type="number"
                    value={formSemesters}
                    onChange={(e) => setFormSemesters(Number(e.target.value))}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:border-[#C8A45D] focus:outline-hidden"
                  />
                </div>
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Total Credits</label>
                  <input
                    type="number"
                    value={formCredits}
                    onChange={(e) => setFormCredits(Number(e.target.value))}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:border-[#C8A45D] focus:outline-hidden"
                  />
                </div>
              </div>

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