import { useMemo, useState } from "react";
import {
  BookOpen,
  Plus,
  Search,
  Calendar,
  GraduationCap,
  Users,
  ClipboardList,
  Filter,
  X,
  CheckCircle2,
  Clock3,
  FileText,
  Trash2,
  Eye,
  RotateCcw,
} from "lucide-react";

const classes = [
  "Nursery",
  "LKG",
  "UKG",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "10",
];

const sections = ["A", "B", "C"];

const subjectsByClass = {
  Nursery: ["English", "Math", "Drawing"],
  LKG: ["English", "Math", "EVS"],
  UKG: ["English", "Math", "GK"],
  1: ["English", "Hindi", "Math", "EVS"],
  2: ["English", "Hindi", "Math", "EVS"],
  3: ["English", "Hindi", "Math", "Science", "SST"],
  4: ["English", "Hindi", "Math", "Science", "SST"],
  5: ["English", "Hindi", "Math", "Science", "SST"],
  6: ["English", "Hindi", "Math", "Science", "SST", "Computer"],
  7: ["English", "Hindi", "Math", "Science", "SST", "Computer"],
  8: ["English", "Hindi", "Math", "Science", "SST", "Computer"],
  9: [
    "English",
    "Hindi",
    "Math",
    "Physics",
    "Chemistry",
    "Biology",
    "SST",
    "Computer",
  ],
  10: [
    "English",
    "Hindi",
    "Math",
    "Physics",
    "Chemistry",
    "Biology",
    "SST",
    "Computer",
  ],
};

const teachers = [
  "Rahul Sharma",
  "Neha Verma",
  "Anjali Gupta",
  "Rohit Mehta",
  "Priya Singh",
];

const initialHomework = [
  {
    id: 1,
    title: "Learn Tables 2 to 5",
    className: "3",
    section: "A",
    subject: "Math",
    teacher: "Rahul Sharma",
    dueDate: "2026-06-12",
    description: "Complete notebook work and revise tables.",
    status: "Upcoming",
  },
  {
    id: 2,
    title: "Science Chapter 3",
    className: "8",
    section: "B",
    subject: "Science",
    teacher: "Neha Verma",
    dueDate: "2026-05-01",
    description: "Read chapter and solve back exercises.",
    status: "Closed",
  },
  {
    id: 3,
    title: "Essay Writing",
    className: "6",
    section: "C",
    subject: "English",
    teacher: "Anjali Gupta",
    dueDate: "2026-06-18",
    description: "Write essay on My School.",
    status: "Upcoming",
  },
];

const InputField = ({ label, value, onChange, placeholder, type = "text" }) => (
  <div>
    <label className="text-xs font-semibold text-gray-500 uppercase mb-2 block">
      {label}
    </label>

    <input
      type={type}
      value={value}
      placeholder={placeholder}
      onChange={(e) => onChange(e.target.value)}
      className="w-full h-11 px-4 rounded-2xl border border-gray-200 bg-white text-sm outline-none focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all"
    />
  </div>
);

const SelectField = ({ label, value, onChange, options }) => (
  <div>
    <label className="text-xs font-semibold text-gray-500 uppercase mb-2 block">
      {label}
    </label>

    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className="w-full h-11 px-4 rounded-2xl border border-gray-200 bg-white text-sm outline-none focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all"
    >
      <option value="">Select {label}</option>

      {options.map((item) => (
        <option key={item}>{item}</option>
      ))}
    </select>
  </div>
);

export default function AddHomework() {
  const [homeworkData, setHomeworkData] = useState(initialHomework);

  const [search, setSearch] = useState("");

  const [statusFilter, setStatusFilter] = useState("Upcoming");

  const [filters, setFilters] = useState({
    class: "",
    section: "",
    subject: "",
    teacher: "",
  });

  const [showModal, setShowModal] = useState(false);

  const [viewHomework, setViewHomework] = useState(null);

  const [form, setForm] = useState({
    title: "",
    className: "",
    section: "",
    subject: "",
    teacher: "",
    dueDate: "",
    description: "",
  });

  const filteredHomework = useMemo(() => {
    return homeworkData.filter((item) => {
      const matchesClass =
        filters.class === "" || item.className === filters.class;

      const matchesSection =
        filters.section === "" || item.section === filters.section;

      const matchesSubject =
        filters.subject === "" || item.subject === filters.subject;

      const matchesTeacher =
        filters.teacher === "" || item.teacher === filters.teacher;

      const matchesSearch =
        search === "" ||
        item.title.toLowerCase().includes(search.toLowerCase()) ||
        item.subject.toLowerCase().includes(search.toLowerCase());

      const matchesStatus =
        statusFilter === "All" || item.status === statusFilter;

      return (
        matchesClass &&
        matchesSection &&
        matchesSubject &&
        matchesTeacher &&
        matchesSearch &&
        matchesStatus
      );
    });
  }, [filters, search, homeworkData, statusFilter]);

  const resetFilters = () => {
    setFilters({
      class: "",
      section: "",
      subject: "",
      teacher: "",
    });

    setSearch("");

    setStatusFilter("Upcoming");
  };

  const addHomework = () => {
    if (!form.title || !form.className || !form.subject || !form.teacher) {
      alert("Please fill all required fields");
      return;
    }

    const newHomework = {
      id: Date.now(),
      ...form,
      status: "Upcoming",
    };

    setHomeworkData((prev) => [...prev, newHomework]);

    setForm({
      title: "",
      className: "",
      section: "",
      subject: "",
      teacher: "",
      dueDate: "",
      description: "",
    });

    setShowModal(false);
  };

  const deleteHomework = (id) => {
    setHomeworkData((prev) => prev.filter((item) => item.id !== id));
  };

  const toggleStatus = (id) => {
    setHomeworkData((prev) =>
      prev.map((item) =>
        item.id === id
          ? {
              ...item,
              status: item.status === "Upcoming" ? "Closed" : "Upcoming",
            }
          : item,
      ),
    );
  };

  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-5 mb-8">
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 rounded-3xl bg-blue-600 text-white flex items-center justify-center shadow-lg">
            <ClipboardList size={26} />
          </div>

          <div>
            <h1 className="text-2xl md:text-3xl font-bold text-gray-900">
              Add Homework
            </h1>

            <p className="text-gray-500 text-sm mt-1">
              Manage school homework assignments
            </p>
          </div>
        </div>

        <button
          onClick={() => setShowModal(true)}
          className="h-12 px-6 rounded-2xl bg-blue-600 text-white font-semibold flex items-center justify-center gap-2 hover:bg-blue-700 transition-all shadow-lg"
        >
          <Plus size={18} />
          Add Homework
        </button>
      </div>

      {/* STATUS TABS */}
      <div className="flex flex-wrap items-center gap-3 mb-6">
        <button
          onClick={() => setStatusFilter("Upcoming")}
          className={`px-5 h-11 rounded-2xl text-sm font-semibold transition-all ${
            statusFilter === "Upcoming"
              ? "bg-blue-600 text-white shadow-lg"
              : "bg-white border border-gray-200 text-gray-600"
          }`}
        >
          Upcoming
        </button>

        <button
          onClick={() => setStatusFilter("Closed")}
          className={`px-5 h-11 rounded-2xl text-sm font-semibold transition-all ${
            statusFilter === "Closed"
              ? "bg-red-500 text-white shadow-lg"
              : "bg-white border border-gray-200 text-gray-600"
          }`}
        >
          Closed
        </button>

        <button
          onClick={() => setStatusFilter("All")}
          className={`px-5 h-11 rounded-2xl text-sm font-semibold transition-all ${
            statusFilter === "All"
              ? "bg-gray-900 text-white shadow-lg"
              : "bg-white border border-gray-200 text-gray-600"
          }`}
        >
          All
        </button>
      </div>

      {/* FILTERS */}
      <div className="bg-white rounded-3xl border border-gray-100 p-5 md:p-6 shadow-sm mb-6">
        <div className="flex items-center gap-3 mb-5">
          <div className="w-10 h-10 rounded-2xl bg-blue-100 flex items-center justify-center">
            <Filter className="text-blue-600" size={18} />
          </div>

          <div>
            <h2 className="font-bold text-gray-900">Filter Homework</h2>

            <p className="text-xs text-gray-400">
              Filter by class, subject or teacher
            </p>
          </div>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-5 gap-4">
          <SelectField
            label="Class"
            value={filters.class}
            onChange={(v) =>
              setFilters({
                ...filters,
                class: v,
                subject: "",
              })
            }
            options={classes}
          />

          <SelectField
            label="Section"
            value={filters.section}
            onChange={(v) =>
              setFilters({
                ...filters,
                section: v,
              })
            }
            options={sections}
          />

          <SelectField
            label="Subject"
            value={filters.subject}
            onChange={(v) =>
              setFilters({
                ...filters,
                subject: v,
              })
            }
            options={filters.class ? subjectsByClass[filters.class] : []}
          />

          <SelectField
            label="Teacher"
            value={filters.teacher}
            onChange={(v) =>
              setFilters({
                ...filters,
                teacher: v,
              })
            }
            options={teachers}
          />

          <div>
            <label className="text-xs font-semibold text-gray-500 uppercase mb-2 block">
              Search
            </label>

            <div className="relative">
              <Search
                size={16}
                className="absolute left-4 top-3.5 text-gray-400"
              />

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

        <div className="flex justify-end mt-5">
          <button
            onClick={resetFilters}
            className="h-11 px-5 rounded-2xl border border-gray-200 bg-white text-gray-600 text-sm font-semibold flex items-center gap-2 hover:bg-gray-50 transition-all"
          >
            <RotateCcw size={16} />
            Reset Filters
          </button>
        </div>
      </div>

      {/* CARDS */}
      <div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-5">
        {filteredHomework.map((item) => (
          <div
            key={item.id}
            className="bg-white rounded-3xl border border-gray-100 p-5 shadow-sm hover:shadow-xl transition-all duration-300"
          >
            <div className="flex items-start justify-between gap-4">
              <div>
                <h3 className="text-lg font-bold text-gray-900 line-clamp-1">
                  {item.title}
                </h3>

                <p className="text-sm text-gray-500 mt-1">{item.subject}</p>
              </div>

              <span
                className={`px-3 py-1 rounded-full text-xs font-bold whitespace-nowrap ${
                  item.status === "Upcoming"
                    ? "bg-blue-100 text-blue-700"
                    : "bg-red-100 text-red-600"
                }`}
              >
                {item.status}
              </span>
            </div>

            <div className="mt-5 space-y-3 text-sm">
              <div className="flex items-center gap-2 text-gray-600">
                <GraduationCap size={16} />
                Class {item.className} - {item.section}
              </div>

              <div className="flex items-center gap-2 text-gray-600">
                <Users size={16} />
                {item.teacher}
              </div>

              <div className="flex items-center gap-2 text-gray-600">
                <Calendar size={16} />
                Due: {item.dueDate}
              </div>
            </div>

            <div className="mt-5 pt-4 border-t border-gray-100 flex items-center justify-between">
              <button
                onClick={() => setViewHomework(item)}
                className="h-10 px-4 rounded-xl bg-blue-50 text-blue-600 text-sm font-semibold flex items-center gap-2 hover:bg-blue-100 transition-all"
              >
                <Eye size={16} />
                View
              </button>

              <div className="flex items-center gap-2">
                <button
                  onClick={() => toggleStatus(item.id)}
                  className="w-10 h-10 rounded-xl bg-gray-100 text-gray-600 flex items-center justify-center hover:bg-gray-200 transition-all"
                >
                  <CheckCircle2 size={17} />
                </button>

                <button
                  onClick={() => deleteHomework(item.id)}
                  className="w-10 h-10 rounded-xl bg-red-50 text-red-500 flex items-center justify-center hover:bg-red-100 transition-all"
                >
                  <Trash2 size={17} />
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* EMPTY */}
      {filteredHomework.length === 0 && (
        <div className="bg-white rounded-3xl border border-gray-100 p-14 text-center mt-6">
          <FileText size={50} className="mx-auto text-gray-200 mb-4" />

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

          <p className="text-sm text-gray-400 mt-1">
            Try changing filters or add new homework
          </p>
        </div>
      )}

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

                <p className="text-sm text-gray-400 mt-1">
                  Create new homework assignment
                </p>
              </div>

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

            <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-5">
              <div className="md:col-span-2">
                <InputField
                  label="Homework Title"
                  value={form.title}
                  placeholder="Enter title"
                  onChange={(v) =>
                    setForm({
                      ...form,
                      title: v,
                    })
                  }
                />
              </div>

              <SelectField
                label="Class"
                value={form.className}
                onChange={(v) =>
                  setForm({
                    ...form,
                    className: v,
                    subject: "",
                  })
                }
                options={classes}
              />

              <SelectField
                label="Section"
                value={form.section}
                onChange={(v) =>
                  setForm({
                    ...form,
                    section: v,
                  })
                }
                options={sections}
              />

              <SelectField
                label="Subject"
                value={form.subject}
                onChange={(v) =>
                  setForm({
                    ...form,
                    subject: v,
                  })
                }
                options={form.className ? subjectsByClass[form.className] : []}
              />

              <SelectField
                label="Teacher"
                value={form.teacher}
                onChange={(v) =>
                  setForm({
                    ...form,
                    teacher: v,
                  })
                }
                options={teachers}
              />

              <InputField
                label="Due Date"
                type="date"
                value={form.dueDate}
                onChange={(v) =>
                  setForm({
                    ...form,
                    dueDate: v,
                  })
                }
              />

              <div className="md:col-span-2">
                <label className="text-xs font-semibold text-gray-500 uppercase mb-2 block">
                  Description
                </label>

                <textarea
                  rows={4}
                  value={form.description}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      description: e.target.value,
                    })
                  }
                  placeholder="Enter homework description..."
                  className="w-full rounded-2xl border border-gray-200 p-4 text-sm outline-none focus:ring-4 focus:ring-blue-100 focus:border-blue-500 transition-all resize-none"
                />
              </div>
            </div>

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

              <button
                onClick={addHomework}
                className="h-11 px-6 rounded-2xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition-all shadow-lg"
              >
                Save Homework
              </button>
            </div>
          </div>
        </div>
      )}

      {/* VIEW MODAL */}
      {viewHomework && (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
          <div className="bg-white rounded-3xl w-full max-w-lg shadow-2xl">
            <div className="flex items-center justify-between p-6 border-b border-gray-100">
              <h2 className="text-xl font-bold text-gray-900">
                Homework Details
              </h2>

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

            <div className="p-6 space-y-4">
              {[
                ["Title", viewHomework.title],
                [
                  "Class",
                  `${viewHomework.className} - ${viewHomework.section}`,
                ],
                ["Subject", viewHomework.subject],
                ["Teacher", viewHomework.teacher],
                ["Due Date", viewHomework.dueDate],
                ["Status", viewHomework.status],
                ["Description", viewHomework.description],
              ].map(([label, value]) => (
                <div
                  key={label}
                  className="flex justify-between gap-5 border-b border-gray-100 pb-3"
                >
                  <span className="text-gray-400 text-sm">{label}</span>

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

            <div className="p-6 border-t border-gray-100 flex justify-end">
              <button
                onClick={() => setViewHomework(null)}
                className="h-11 px-6 rounded-2xl bg-blue-600 text-white font-semibold"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
