import { useMemo, useState } from "react";
import {
  Search,
  Users,
  GraduationCap,
  IdCard,
  Printer,
  Download,
  Eye,
  CheckSquare,
  Square,
  Filter,
} from "lucide-react";

const classData = {
  Nursery: ["A", "B"],
  LKG: ["A", "B"],
  UKG: ["A", "B"],
  1: ["A", "B", "C"],
  2: ["A", "B", "C"],
  3: ["A", "B", "C"],
  4: ["A", "B", "C"],
  5: ["A", "B", "C"],
  6: ["A", "B", "C"],
  7: ["A", "B", "C"],
  8: ["A", "B", "C"],
  9: ["A", "B", "C"],
  10: ["A", "B", "C"],
};

const idCardTemplates = [
  "Classic Blue",
  "Modern White",
  "Premium Dark",
  "Student Standard",
];

const studentsData = [
  {
    id: 1,
    admissionNo: "ADM001",
    name: "Aarav Sharma",
    class: "10",
    section: "A",
    father: "Rajesh Sharma",
    dob: "2009-05-12",
    gender: "Male",
    category: "General",
    mobile: "9876543210",
  },
  {
    id: 2,
    admissionNo: "ADM002",
    name: "Priya Patel",
    class: "9",
    section: "B",
    father: "Mahesh Patel",
    dob: "2010-02-18",
    gender: "Female",
    category: "OBC",
    mobile: "9876501234",
  },
  {
    id: 3,
    admissionNo: "ADM003",
    name: "Rohit Verma",
    class: "8",
    section: "C",
    father: "Sanjay Verma",
    dob: "2011-11-25",
    gender: "Male",
    category: "SC",
    mobile: "9876512345",
  },
  {
    id: 4,
    admissionNo: "ADM004",
    name: "Sneha Gupta",
    class: "10",
    section: "A",
    father: "Rakesh Gupta",
    dob: "2009-07-15",
    gender: "Female",
    category: "General",
    mobile: "9876598765",
  },
];

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

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

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

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

export default function GenerateIdCard() {
  const [selectedClass, setSelectedClass] = useState("");
  const [selectedSection, setSelectedSection] = useState("");
  const [selectedTemplate, setSelectedTemplate] = useState("");
  const [search, setSearch] = useState("");
  const [selectedStudents, setSelectedStudents] = useState([]);

  const sections = selectedClass ? classData[selectedClass] : [];

  const filteredStudents = useMemo(() => {
    return studentsData.filter((student) => {
      if (selectedClass && student.class !== selectedClass) return false;

      if (selectedSection && student.section !== selectedSection) return false;

      if (search && !student.name.toLowerCase().includes(search.toLowerCase()))
        return false;

      return true;
    });
  }, [selectedClass, selectedSection, search]);

  const toggleStudent = (id) => {
    setSelectedStudents((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
    );
  };

  const toggleAll = () => {
    if (selectedStudents.length === filteredStudents.length) {
      setSelectedStudents([]);
    } else {
      setSelectedStudents(filteredStudents.map((s) => s.id));
    }
  };

  const handleGenerate = () => {
    if (!selectedTemplate) {
      alert("Please select ID Card Template");
      return;
    }

    if (selectedStudents.length === 0) {
      alert("Please select students");
      return;
    }

    alert(`${selectedStudents.length} ID Cards Generated Successfully`);
  };

  const resetFilters = () => {
    setSelectedClass("");
    setSelectedSection("");
    setSelectedTemplate("");
    setSearch("");
    setSelectedStudents([]);
  };

  return (
    <div className="bg-[#f4f7fb] min-h-screen 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-2xl bg-blue-600 text-white flex items-center justify-center shadow-lg">
            <IdCard size={28} />
          </div>

          <div>
            <h1 className="text-2xl font-bold text-gray-900">
              Generate ID Card
            </h1>

            <p className="text-sm text-gray-500 mt-1">
              Generate and print student ID cards
            </p>
          </div>
        </div>

        <button
          onClick={handleGenerate}
          className="h-11 px-6 rounded-xl bg-blue-600 text-white text-sm font-semibold flex items-center justify-center gap-2 hover:bg-blue-700 transition-all shadow-lg"
        >
          <Printer size={18} />
          Generate ID Cards
        </button>
      </div>

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

          <div>
            <h2 className="text-base font-bold text-gray-900">
              Select Criteria
            </h2>

            <p className="text-xs text-gray-400 mt-0.5">
              Filter students and generate ID cards
            </p>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
          <SelectField
            label="Class"
            icon={GraduationCap}
            value={selectedClass}
            onChange={(v) => {
              setSelectedClass(v);
              setSelectedSection("");
            }}
            options={Object.keys(classData)}
          />

          <SelectField
            label="Section"
            icon={Users}
            value={selectedSection}
            onChange={setSelectedSection}
            options={sections}
          />

          <SelectField
            label="ID Card Template"
            icon={IdCard}
            value={selectedTemplate}
            onChange={setSelectedTemplate}
            options={idCardTemplates}
          />

          <div>
            <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5 block">
              Search Student
            </label>

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

              <input
                type="text"
                placeholder="Search student..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full h-11 rounded-xl border border-gray-200 bg-white pl-10 pr-4 text-sm outline-none focus:ring-2 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-10 px-5 rounded-xl border border-gray-200 bg-white text-sm font-medium text-gray-600 hover:bg-gray-50 transition-all"
          >
            Reset Filters
          </button>
        </div>
      </div>

      {/* Student List */}
      <div className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="px-5 md:px-6 py-4 border-b border-gray-100 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div>
            <h2 className="text-base font-bold text-gray-900">Student List</h2>

            <p className="text-xs text-gray-400 mt-1">
              {filteredStudents.length} students found
            </p>
          </div>

          <button
            onClick={toggleAll}
            className="h-10 px-4 rounded-xl border border-gray-200 bg-white text-sm font-medium text-gray-700 flex items-center gap-2 hover:bg-gray-50 transition-all"
          >
            {selectedStudents.length === filteredStudents.length ? (
              <>
                <CheckSquare size={16} />
                Unselect All
              </>
            ) : (
              <>
                <Square size={16} />
                Select All
              </>
            )}
          </button>
        </div>

        {/* Responsive Cards */}
        <div className="p-4 md:p-6">
          <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
            {filteredStudents.map((student) => {
              const selected = selectedStudents.includes(student.id);

              return (
                <div
                  key={student.id}
                  className={`rounded-2xl border transition-all p-5 ${
                    selected
                      ? "border-blue-500 bg-blue-50"
                      : "border-gray-100 bg-white hover:border-blue-200"
                  }`}
                >
                  <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                    <div className="flex items-start gap-4 min-w-0">
                      <button
                        onClick={() => toggleStudent(student.id)}
                        className="mt-1"
                      >
                        {selected ? (
                          <CheckSquare size={20} className="text-blue-600" />
                        ) : (
                          <Square size={20} className="text-gray-400" />
                        )}
                      </button>

                      <div className="min-w-0">
                        <h3 className="text-base font-bold text-gray-900 truncate">
                          {student.name}
                        </h3>

                        <p className="text-sm text-gray-500 mt-1">
                          Admission No: {student.admissionNo}
                        </p>

                        <div className="flex flex-wrap gap-2 mt-3">
                          <span className="px-3 py-1 rounded-full bg-blue-100 text-blue-700 text-xs font-semibold">
                            Class {student.class} - {student.section}
                          </span>

                          <span className="px-3 py-1 rounded-full bg-purple-100 text-purple-700 text-xs font-semibold">
                            {student.gender}
                          </span>

                          <span className="px-3 py-1 rounded-full bg-green-100 text-green-700 text-xs font-semibold">
                            {student.category}
                          </span>
                        </div>
                      </div>
                    </div>

                    <button className="h-10 px-4 rounded-xl bg-gray-100 text-gray-700 text-sm font-medium flex items-center justify-center gap-2 hover:bg-gray-200 transition-all">
                      <Eye size={16} />
                      Preview
                    </button>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mt-5">
                    <div className="bg-gray-50 rounded-xl p-3">
                      <p className="text-xs text-gray-400 mb-1">Father Name</p>

                      <p className="text-sm font-semibold text-gray-800">
                        {student.father}
                      </p>
                    </div>

                    <div className="bg-gray-50 rounded-xl p-3">
                      <p className="text-xs text-gray-400 mb-1">
                        Mobile Number
                      </p>

                      <p className="text-sm font-semibold text-gray-800">
                        {student.mobile}
                      </p>
                    </div>

                    <div className="bg-gray-50 rounded-xl p-3 md:col-span-2">
                      <p className="text-xs text-gray-400 mb-1">
                        Date Of Birth
                      </p>

                      <p className="text-sm font-semibold text-gray-800">
                        {student.dob}
                      </p>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {filteredStudents.length === 0 && (
            <div className="py-20 text-center">
              <Users size={55} className="mx-auto text-gray-200 mb-4" />

              <h3 className="text-lg font-bold text-gray-600">
                No Students Found
              </h3>

              <p className="text-sm text-gray-400 mt-1">
                Try changing filters or search keyword
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
