import { useMemo, useState } from "react";
import {
  Search,
  Plus,
  Edit,
  Trash2,
  BookOpen,
  CheckCircle2,
  Clock3,
  FileQuestion,
  Filter,
  X,
  Save,
} from "lucide-react";

const initialQuestions = [
  {
    id: 1,
    question: "What is the capital city of India?",
    subject: "Social Science",
    class: "6",
    difficulty: "Easy",
    marks: 2,
    type: "MCQ",
    status: "Active",
  },
  {
    id: 2,
    question: "Explain Newton's First Law of Motion with example.",
    subject: "Science",
    class: "9",
    difficulty: "Medium",
    marks: 5,
    type: "Descriptive",
    status: "Active",
  },
  {
    id: 3,
    question: "Solve: 5x + 7 = 22",
    subject: "Mathematics",
    class: "7",
    difficulty: "Easy",
    marks: 3,
    type: "Short Answer",
    status: "Draft",
  },
];

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

const subjects = [
  "English",
  "Hindi",
  "Mathematics",
  "Science",
  "Social Science",
  "Computer",
  "EVS",
  "GK",
];

export default function QuestionBank() {
  const [questions, setQuestions] = useState(initialQuestions);
  const [search, setSearch] = useState("");
  const [selectedClass, setSelectedClass] = useState("");
  const [selectedSubject, setSelectedSubject] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("");
  const [showModal, setShowModal] = useState(false);

  const [formData, setFormData] = useState({
    question: "",
    subject: "",
    class: "",
    difficulty: "",
    marks: "",
    type: "",
    status: "Active",
  });

  const filteredQuestions = useMemo(() => {
    return questions.filter((item) => {
      const matchesSearch =
        item.question.toLowerCase().includes(search.toLowerCase()) ||
        item.subject.toLowerCase().includes(search.toLowerCase());

      const matchesClass = !selectedClass || item.class === selectedClass;

      const matchesSubject =
        !selectedSubject || item.subject === selectedSubject;

      const matchesStatus = !selectedStatus || item.status === selectedStatus;

      return matchesSearch && matchesClass && matchesSubject && matchesStatus;
    });
  }, [questions, search, selectedClass, selectedSubject, selectedStatus]);

  const stats = {
    total: questions.length,
    active: questions.filter((q) => q.status === "Active").length,
    draft: questions.filter((q) => q.status === "Draft").length,
  };

  const handleAddQuestion = () => {
    if (!formData.question || !formData.subject || !formData.class) {
      alert("Please fill required fields");
      return;
    }

    setQuestions([
      ...questions,
      {
        ...formData,
        id: Date.now(),
      },
    ]);

    setFormData({
      question: "",
      subject: "",
      class: "",
      difficulty: "",
      marks: "",
      type: "",
      status: "Active",
    });

    setShowModal(false);
  };

  const deleteQuestion = (id) => {
    setQuestions(questions.filter((item) => item.id !== id));
  };

  const resetFilters = () => {
    setSearch("");
    setSelectedClass("");
    setSelectedSubject("");
    setSelectedStatus("");
  };

  return (
    <div className="min-h-screen bg-[#f4f7fb] p-4 md:p-6 overflow-x-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">
            <BookOpen size={28} />
          </div>

          <div>
            <h1 className="text-2xl md:text-3xl font-bold text-gray-900">
              Question Bank
            </h1>
            <p className="text-sm text-gray-500 mt-1">
              Manage school questions with modern dashboard
            </p>
          </div>
        </div>

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

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4 mb-6">
        <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-500 text-sm">Total Questions</p>
              <h2 className="text-3xl font-bold mt-2 text-gray-900">
                {stats.total}
              </h2>
            </div>

            <div className="w-14 h-14 rounded-2xl bg-blue-100 flex items-center justify-center">
              <FileQuestion className="text-blue-600" size={28} />
            </div>
          </div>
        </div>

        <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-500 text-sm">Active Questions</p>
              <h2 className="text-3xl font-bold mt-2 text-green-600">
                {stats.active}
              </h2>
            </div>

            <div className="w-14 h-14 rounded-2xl bg-green-100 flex items-center justify-center">
              <CheckCircle2 className="text-green-600" size={28} />
            </div>
          </div>
        </div>

        <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-500 text-sm">Draft Questions</p>
              <h2 className="text-3xl font-bold mt-2 text-orange-500">
                {stats.draft}
              </h2>
            </div>

            <div className="w-14 h-14 rounded-2xl bg-orange-100 flex items-center justify-center">
              <Clock3 className="text-orange-500" size={28} />
            </div>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 mb-6">
        <div className="flex items-center gap-2 mb-5">
          <Filter className="text-blue-600" size={20} />
          <h2 className="text-lg font-bold text-gray-800">Filters</h2>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
          <div className="relative">
            <Search
              size={18}
              className="absolute left-3 top-3.5 text-gray-400"
            />

            <input
              type="text"
              placeholder="Search question..."
              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"
            />
          </div>

          <select
            value={selectedClass}
            onChange={(e) => setSelectedClass(e.target.value)}
            className="w-full h-11 rounded-xl border border-gray-200 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
          >
            <option value="">All Classes</option>

            {classes.map((cls) => (
              <option key={cls}>{cls}</option>
            ))}
          </select>

          <select
            value={selectedSubject}
            onChange={(e) => setSelectedSubject(e.target.value)}
            className="w-full h-11 rounded-xl border border-gray-200 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
          >
            <option value="">All Subjects</option>

            {subjects.map((sub) => (
              <option key={sub}>{sub}</option>
            ))}
          </select>

          <div className="flex gap-3">
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="flex-1 h-11 rounded-xl border border-gray-200 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
            >
              <option value="">All Status</option>
              <option>Active</option>
              <option>Draft</option>
            </select>

            <button
              onClick={resetFilters}
              className="h-11 px-4 rounded-xl border border-gray-200 bg-gray-50 hover:bg-gray-100 text-sm font-semibold text-gray-700 transition-all whitespace-nowrap"
            >
              Reset
            </button>
          </div>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-100">
              <tr>
                {[
                  "Question",
                  "Subject",
                  "Class",
                  "Difficulty",
                  "Marks",
                  "Type",
                  "Status",
                  "Action",
                ].map((head) => (
                  <th
                    key={head}
                    className="px-4 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-500 whitespace-nowrap"
                  >
                    {head}
                  </th>
                ))}
              </tr>
            </thead>

            <tbody>
              {filteredQuestions.map((item) => (
                <tr
                  key={item.id}
                  className="border-b border-gray-100 hover:bg-blue-50/40 transition-all"
                >
                  <td className="px-4 py-4 min-w-[260px]">
                    <p className="text-sm font-medium text-gray-800 leading-relaxed break-words">
                      {item.question}
                    </p>
                  </td>

                  <td className="px-4 py-4 whitespace-nowrap">
                    <span className="px-3 py-1 rounded-full bg-blue-100 text-blue-700 text-xs font-semibold">
                      {item.subject}
                    </span>
                  </td>

                  <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-700">
                    Class {item.class}
                  </td>

                  <td className="px-4 py-4 whitespace-nowrap">
                    <span
                      className={`px-3 py-1 rounded-full text-xs font-semibold ${
                        item.difficulty === "Easy"
                          ? "bg-green-100 text-green-700"
                          : item.difficulty === "Medium"
                            ? "bg-yellow-100 text-yellow-700"
                            : "bg-red-100 text-red-700"
                      }`}
                    >
                      {item.difficulty}
                    </span>
                  </td>

                  <td className="px-4 py-4 whitespace-nowrap text-sm font-semibold text-gray-700">
                    {item.marks}
                  </td>

                  <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-700">
                    {item.type}
                  </td>

                  <td className="px-4 py-4 whitespace-nowrap">
                    <span
                      className={`px-3 py-1 rounded-full text-xs font-bold ${
                        item.status === "Active"
                          ? "bg-green-100 text-green-700"
                          : "bg-orange-100 text-orange-700"
                      }`}
                    >
                      {item.status}
                    </span>
                  </td>

                  <td className="px-4 py-4 whitespace-nowrap">
                    <div className="flex items-center gap-2">
                      <button className="w-9 h-9 rounded-xl bg-blue-100 text-blue-600 flex items-center justify-center hover:scale-105 transition-all">
                        <Edit size={16} />
                      </button>

                      <button
                        onClick={() => deleteQuestion(item.id)}
                        className="w-9 h-9 rounded-xl bg-red-100 text-red-600 flex items-center justify-center hover:scale-105 transition-all"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filteredQuestions.length === 0 && (
          <div className="py-20 text-center">
            <FileQuestion size={60} className="mx-auto text-gray-300 mb-4" />

            <h3 className="text-xl font-bold text-gray-700">
              No Questions Found
            </h3>

            <p className="text-sm text-gray-400 mt-2">
              Try changing your filters or search.
            </p>
          </div>
        )}
      </div>

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

              <button
                onClick={() => setShowModal(false)}
                className="w-10 h-10 rounded-xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center transition-all"
              >
                <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">
                <label className="text-sm font-semibold text-gray-700 mb-2 block">
                  Question *
                </label>

                <textarea
                  rows={5}
                  value={formData.question}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      question: e.target.value,
                    })
                  }
                  placeholder="Enter question..."
                  className="w-full rounded-2xl border border-gray-200 p-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
                />
              </div>

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

                <select
                  value={formData.subject}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      subject: e.target.value,
                    })
                  }
                  className="w-full h-11 rounded-xl border border-gray-200 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
                >
                  <option value="">Select Subject</option>

                  {subjects.map((sub) => (
                    <option key={sub}>{sub}</option>
                  ))}
                </select>
              </div>

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

                <select
                  value={formData.class}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      class: e.target.value,
                    })
                  }
                  className="w-full h-11 rounded-xl border border-gray-200 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
                >
                  <option value="">Select Class</option>

                  {classes.map((cls) => (
                    <option key={cls}>{cls}</option>
                  ))}
                </select>
              </div>

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

                <select
                  value={formData.difficulty}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      difficulty: e.target.value,
                    })
                  }
                  className="w-full h-11 rounded-xl border border-gray-200 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
                >
                  <option value="">Select Difficulty</option>
                  <option>Easy</option>
                  <option>Medium</option>
                  <option>Hard</option>
                </select>
              </div>

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

                <input
                  type="number"
                  value={formData.marks}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      marks: e.target.value,
                    })
                  }
                  placeholder="Enter marks"
                  className="w-full h-11 rounded-xl border border-gray-200 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
                />
              </div>

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

                <select
                  value={formData.type}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      type: e.target.value,
                    })
                  }
                  className="w-full h-11 rounded-xl border border-gray-200 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
                >
                  <option value="">Select Type</option>
                  <option>MCQ</option>
                  <option>Short Answer</option>
                  <option>Descriptive</option>
                </select>
              </div>

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

                <select
                  value={formData.status}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      status: e.target.value,
                    })
                  }
                  className="w-full h-11 rounded-xl border border-gray-200 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100"
                >
                  <option>Active</option>
                  <option>Draft</option>
                </select>
              </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-xl border border-gray-200 text-gray-700 hover:bg-gray-50 transition-all"
              >
                Cancel
              </button>

              <button
                onClick={handleAddQuestion}
                className="h-11 px-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-semibold flex items-center gap-2 transition-all shadow-lg"
              >
                <Save size={18} />
                Save Question
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
