import { useMemo, useState } from "react";
import {
  Search,
  BookOpen,
  Clock3,
  CalendarDays,
  FileText,
  Eye,
  Trash2,
  Plus,
  CheckCircle2,
  TimerReset,
  X,
  ClipboardList,
  GraduationCap,
  BadgeCheck,
} from "lucide-react";

const initialExams = [
  {
    id: 1,
    exam: "Annual Exam",
    quiz: 0,
    questions: 1,
    descriptive: 0,
    attempt: 100,
    examFrom: "05/01/2026 08:00 AM",
    examTo: "05/30/2026 11:00 AM",
    duration: "00:03:00",
    examPublished: "Yes",
    resultPublished: "Pending",
    status: "Upcoming",
    class: "10",
    subject: "Mathematics",
    description:
      "The Annual Examination is conducted at the end of the academic year to assess the overall learning and understanding of students across all subjects.",
  },
  {
    id: 2,
    exam: "Science Weekly Test",
    quiz: 20,
    questions: 20,
    descriptive: 5,
    attempt: 78,
    examFrom: "06/05/2026 09:00 AM",
    examTo: "06/05/2026 10:00 AM",
    duration: "01:00:00",
    examPublished: "Yes",
    resultPublished: "Yes",
    status: "Closed",
    class: "9",
    subject: "Science",
    description:
      "Weekly online science test including MCQ and descriptive questions for physics, chemistry and biology topics.",
  },
];

const emptyForm = {
  exam: "",
  class: "",
  subject: "",
  questions: "",
  descriptive: "",
  attempt: "",
  examFrom: "",
  examTo: "",
  duration: "",
  examPublished: "Yes",
  resultPublished: "Pending",
  status: "Upcoming",
  description: "",
};

export default function OnlineExamList() {
  const [examList, setExamList] = useState(initialExams);
  const [search, setSearch] = useState("");
  const [tab, setTab] = useState("Upcoming");
  const [showModal, setShowModal] = useState(false);
  const [viewExam, setViewExam] = useState(null);

  const [form, setForm] = useState(emptyForm);

  const filteredExams = useMemo(() => {
    return examList.filter(
      (item) =>
        item.status === tab &&
        (item.exam.toLowerCase().includes(search.toLowerCase()) ||
          item.subject.toLowerCase().includes(search.toLowerCase()) ||
          item.class.toLowerCase().includes(search.toLowerCase())),
    );
  }, [examList, search, tab]);

  const stats = {
    total: examList.length,
    upcoming: examList.filter((e) => e.status === "Upcoming").length,
    closed: examList.filter((e) => e.status === "Closed").length,
    published: examList.filter((e) => e.examPublished === "Yes").length,
  };

  const saveExam = () => {
    if (!form.exam || !form.class || !form.subject || !form.examFrom) {
      return alert("Please fill all required fields");
    }

    setExamList((prev) => [
      ...prev,
      {
        ...form,
        id: Date.now(),
        quiz: 0,
      },
    ]);

    setForm(emptyForm);
    setShowModal(false);
  };

  const deleteExam = (id) => {
    if (window.confirm("Delete this exam?")) {
      setExamList((prev) => prev.filter((item) => item.id !== id));
    }
  };

  return (
    <div className="min-h-screen bg-[#f4f7fb] p-4 md:p-6 overflow-hidden">
      {/* Header */}
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 rounded-3xl bg-gradient-to-br from-indigo-600 to-blue-600 text-white flex items-center justify-center shadow-xl">
            <ClipboardList size={28} />
          </div>

          <div>
            <h1 className="text-2xl md:text-3xl font-bold text-gray-900">
              Online Exam List
            </h1>

            <p className="text-sm text-gray-500 mt-1">
              Manage upcoming and closed online examinations
            </p>
          </div>
        </div>

        <button
          onClick={() => setShowModal(true)}
          className="h-11 px-5 rounded-2xl bg-gradient-to-r from-indigo-600 to-blue-600 text-white font-semibold flex items-center gap-2 shadow-lg hover:scale-[1.02] transition-all"
        >
          <Plus size={18} />
          Add Online Exam
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-4 mb-6">
        {[
          {
            title: "Total Exams",
            value: stats.total,
            icon: FileText,
            bg: "bg-blue-100",
            color: "text-blue-600",
          },
          {
            title: "Upcoming",
            value: stats.upcoming,
            icon: CalendarDays,
            bg: "bg-green-100",
            color: "text-green-600",
          },
          {
            title: "Closed",
            value: stats.closed,
            icon: CheckCircle2,
            bg: "bg-red-100",
            color: "text-red-600",
          },
          {
            title: "Published",
            value: stats.published,
            icon: BadgeCheck,
            bg: "bg-purple-100",
            color: "text-purple-600",
          },
        ].map((item) => {
          const Icon = item.icon;

          return (
            <div
              key={item.title}
              className="bg-white rounded-3xl border border-gray-100 shadow-sm p-5 flex items-center justify-between"
            >
              <div>
                <p className="text-sm text-gray-500 font-medium">
                  {item.title}
                </p>

                <h2 className="text-3xl font-bold text-gray-900 mt-2">
                  {item.value}
                </h2>
              </div>

              <div
                className={`w-14 h-14 rounded-2xl ${item.bg} flex items-center justify-center`}
              >
                <Icon className={item.color} size={26} />
              </div>
            </div>
          );
        })}
      </div>

      {/* Filter Section */}
      <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-5 mb-6">
        <div className="flex flex-col lg:flex-row gap-4 lg:items-center lg:justify-between">
          {/* Tabs */}
          <div className="flex flex-wrap gap-3">
            {["Upcoming", "Closed"].map((item) => (
              <button
                key={item}
                onClick={() => setTab(item)}
                className={`h-11 px-5 rounded-2xl text-sm font-semibold transition-all ${
                  tab === item
                    ? "bg-gradient-to-r from-indigo-600 to-blue-600 text-white shadow-lg"
                    : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                }`}
              >
                {item} Exams
              </button>
            ))}
          </div>

          {/* Search */}
          <div className="relative w-full lg:w-96">
            <Search
              size={18}
              className="absolute left-4 top-3.5 text-gray-400"
            />

            <input
              type="text"
              placeholder="Search exams..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full h-12 rounded-2xl border border-gray-200 bg-gray-50 pl-11 pr-4 text-sm outline-none focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 transition-all"
            />
          </div>
        </div>
      </div>

      {/* Exam Cards */}
      <div className="space-y-5">
        {filteredExams.map((item) => (
          <div
            key={item.id}
            className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden hover:shadow-xl transition-all"
          >
            {/* Top */}
            <div className="bg-gradient-to-r from-indigo-600 to-blue-600 p-5 text-white">
              <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
                <div>
                  <h2 className="text-2xl font-bold">{item.exam}</h2>

                  <p className="text-indigo-100 mt-1 text-sm">
                    {item.subject} • Class {item.class}
                  </p>
                </div>

                <span
                  className={`px-4 py-2 rounded-full text-xs font-bold w-fit ${
                    item.status === "Upcoming"
                      ? "bg-green-100 text-green-700"
                      : "bg-red-100 text-red-700"
                  }`}
                >
                  {item.status}
                </span>
              </div>
            </div>

            {/* Content */}
            <div className="p-5">
              {/* Grid */}
              <div className="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-8 gap-4 mb-5">
                {[
                  {
                    label: "Quiz",
                    value: item.quiz,
                    icon: BookOpen,
                  },
                  {
                    label: "Questions",
                    value: item.questions,
                    icon: FileText,
                  },
                  {
                    label: "Attempt",
                    value: `${item.attempt}%`,
                    icon: GraduationCap,
                  },
                  {
                    label: "Duration",
                    value: item.duration,
                    icon: Clock3,
                  },
                  {
                    label: "Exam Published",
                    value: item.examPublished,
                    icon: CheckCircle2,
                  },
                  {
                    label: "Result Published",
                    value: item.resultPublished,
                    icon: BadgeCheck,
                  },
                ].map((card, index) => {
                  const Icon = card.icon;

                  return (
                    <div key={index} className="bg-gray-50 rounded-2xl p-4">
                      <div className="flex items-center gap-2 mb-2">
                        <Icon size={15} className="text-indigo-600" />

                        <p className="text-xs text-gray-500 font-medium">
                          {card.label}
                        </p>
                      </div>

                      <h3 className="text-lg font-bold text-gray-900">
                        {card.value}
                      </h3>
                    </div>
                  );
                })}
              </div>

              {/* Dates */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-5">
                <div className="bg-indigo-50 rounded-2xl p-4">
                  <p className="text-xs font-semibold text-indigo-600 uppercase">
                    Exam From
                  </p>

                  <h3 className="text-sm font-bold text-gray-900 mt-2">
                    {item.examFrom}
                  </h3>
                </div>

                <div className="bg-blue-50 rounded-2xl p-4">
                  <p className="text-xs font-semibold text-blue-600 uppercase">
                    Exam To
                  </p>

                  <h3 className="text-sm font-bold text-gray-900 mt-2">
                    {item.examTo}
                  </h3>
                </div>
              </div>

              {/* Description */}
              <div className="bg-gray-50 rounded-2xl p-5">
                <h3 className="text-sm font-bold text-gray-900 mb-2">
                  Description
                </h3>

                <p className="text-sm text-gray-600 leading-7">
                  {item.description}
                </p>
              </div>

              {/* Actions */}
              <div className="flex justify-end gap-3 mt-5">
                <button
                  onClick={() => setViewExam(item)}
                  className="w-11 h-11 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center hover:scale-105 transition-all"
                >
                  <Eye size={18} />
                </button>

                <button className="w-11 h-11 rounded-2xl bg-yellow-50 text-yellow-600 flex items-center justify-center hover:scale-105 transition-all">
                  <TimerReset size={18} />
                </button>

                <button
                  onClick={() => deleteExam(item.id)}
                  className="w-11 h-11 rounded-2xl bg-red-50 text-red-500 flex items-center justify-center hover:scale-105 transition-all"
                >
                  <Trash2 size={18} />
                </button>
              </div>
            </div>
          </div>
        ))}

        {filteredExams.length === 0 && (
          <div className="bg-white rounded-3xl border border-dashed border-gray-300 py-20 text-center">
            <ClipboardList size={60} className="mx-auto text-gray-300 mb-4" />

            <h2 className="text-xl font-bold text-gray-700">No Exams Found</h2>

            <p className="text-sm text-gray-400 mt-2">
              Try changing search or add a new online exam.
            </p>
          </div>
        )}
      </div>

      {/* Add Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
            {/* Header */}
            <div className="flex items-center justify-between p-6 border-b border-gray-100">
              <div>
                <h2 className="text-2xl font-bold text-gray-900">
                  Add Online Exam
                </h2>

                <p className="text-sm text-gray-500 mt-1">
                  Create and publish new online examination
                </p>
              </div>

              <button
                onClick={() => setShowModal(false)}
                className="w-10 h-10 rounded-xl bg-gray-100 flex items-center justify-center hover:bg-gray-200"
              >
                <X size={18} />
              </button>
            </div>

            {/* Form */}
            <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-5">
              {[
                {
                  label: "Exam Name *",
                  key: "exam",
                },
                {
                  label: "Subject *",
                  key: "subject",
                },
                {
                  label: "Questions",
                  key: "questions",
                  type: "number",
                },
                {
                  label: "Descriptive",
                  key: "descriptive",
                  type: "number",
                },
                {
                  label: "Attempt %",
                  key: "attempt",
                  type: "number",
                },
                {
                  label: "Duration",
                  key: "duration",
                },
              ].map((field) => (
                <div key={field.key}>
                  <label className="text-sm font-semibold text-gray-700 mb-2 block">
                    {field.label}
                  </label>

                  <input
                    type={field.type || "text"}
                    value={form[field.key]}
                    onChange={(e) =>
                      setForm({
                        ...form,
                        [field.key]: e.target.value,
                      })
                    }
                    className="w-full h-12 rounded-2xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 transition-all"
                  />
                </div>
              ))}

              {/* Class */}
              <div>
                <label className="text-sm font-semibold text-gray-700 mb-2 block">
                  Class *
                </label>

                <select
                  value={form.class}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      class: e.target.value,
                    })
                  }
                  className="w-full h-12 rounded-2xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none"
                >
                  <option value="">Select Class</option>

                  {[
                    "Nursery",
                    "LKG",
                    "UKG",
                    "1",
                    "2",
                    "3",
                    "4",
                    "5",
                    "6",
                    "7",
                    "8",
                    "9",
                    "10",
                  ].map((cls) => (
                    <option key={cls}>{cls}</option>
                  ))}
                </select>
              </div>

              {/* Status */}
              <div>
                <label className="text-sm font-semibold text-gray-700 mb-2 block">
                  Status
                </label>

                <select
                  value={form.status}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      status: e.target.value,
                    })
                  }
                  className="w-full h-12 rounded-2xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none"
                >
                  <option>Upcoming</option>
                  <option>Closed</option>
                </select>
              </div>

              {/* Dates */}
              <div>
                <label className="text-sm font-semibold text-gray-700 mb-2 block">
                  Exam From *
                </label>

                <input
                  type="datetime-local"
                  value={form.examFrom}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      examFrom: e.target.value,
                    })
                  }
                  className="w-full h-12 rounded-2xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none"
                />
              </div>

              <div>
                <label className="text-sm font-semibold text-gray-700 mb-2 block">
                  Exam To
                </label>

                <input
                  type="datetime-local"
                  value={form.examTo}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      examTo: e.target.value,
                    })
                  }
                  className="w-full h-12 rounded-2xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none"
                />
              </div>

              {/* Description */}
              <div className="md:col-span-2">
                <label className="text-sm font-semibold text-gray-700 mb-2 block">
                  Description
                </label>

                <textarea
                  rows={5}
                  value={form.description}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      description: e.target.value,
                    })
                  }
                  className="w-full rounded-2xl border border-gray-200 bg-gray-50 p-4 text-sm outline-none resize-none"
                />
              </div>
            </div>

            {/* Footer */}
            <div className="flex justify-end gap-3 p-6 border-t border-gray-100">
              <button
                onClick={() => setShowModal(false)}
                className="h-11 px-5 rounded-2xl border border-gray-200 text-gray-600 font-semibold hover:bg-gray-50"
              >
                Cancel
              </button>

              <button
                onClick={saveExam}
                className="h-11 px-6 rounded-2xl bg-gradient-to-r from-indigo-600 to-blue-600 text-white font-semibold shadow-lg hover:scale-[1.02] transition-all"
              >
                Save Exam
              </button>
            </div>
          </div>
        </div>
      )}

      {/* View Modal */}
      {viewExam && (
        <div className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-2xl overflow-hidden">
            {/* Header */}
            <div className="bg-gradient-to-r from-indigo-600 to-blue-600 p-6 text-white flex items-center justify-between">
              <div>
                <h2 className="text-2xl font-bold">{viewExam.exam}</h2>

                <p className="text-sm text-indigo-100 mt-1">
                  Online Examination Details
                </p>
              </div>

              <button
                onClick={() => setViewExam(null)}
                className="w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center"
              >
                <X size={18} />
              </button>
            </div>

            {/* Body */}
            <div className="p-6 space-y-4">
              {[
                ["Class", viewExam.class],
                ["Subject", viewExam.subject],
                ["Questions", viewExam.questions],
                ["Duration", viewExam.duration],
                ["Exam From", viewExam.examFrom],
                ["Exam To", viewExam.examTo],
                ["Attempt", `${viewExam.attempt}%`],
                ["Status", viewExam.status],
              ].map(([label, value]) => (
                <div
                  key={label}
                  className="flex justify-between items-center border-b border-gray-100 pb-3"
                >
                  <span className="text-gray-500 text-sm">{label}</span>

                  <span className="font-semibold text-gray-900 text-sm">
                    {value}
                  </span>
                </div>
              ))}

              <div className="bg-gray-50 rounded-2xl p-5 mt-4">
                <h3 className="font-bold text-gray-900 mb-2">Description</h3>

                <p className="text-sm text-gray-600 leading-7">
                  {viewExam.description}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
