import { useMemo, useState } from "react";

/* ================= SAMPLE DATA ================= */
const initialLessons = [
  {
    id: 1,
    className: "LKG",
    section: "A",
    subjectGroup: "English",
    subject: "002",
    lesson: "Hello I am",
  },
  {
    id: 2,
    className: "Nursery",
    section: "A",
    subjectGroup: "Hindi",
    subject: "001",
    lesson: "Greetings and introduction",
  },
];

/* ================= OPTIONS ================= */
const CLASSES = ["Nursery", "LKG", "UKG", "1st", "2nd", "3rd", "4th", "5th"];
const SECTIONS = ["A", "B", "C"];
const SUBJECT_GROUPS = ["English", "Hindi", "Maths", "Science", "Computer"];
const SUBJECTS = ["001", "002", "003", "004", "005"];

/* ================= COMPONENT ================= */
export default function Lesson() {
  const [lessons, setLessons] = useState(initialLessons);

  const [form, setForm] = useState({
    className: "",
    section: "",
    subjectGroup: "",
    subject: "",
    lesson: "",
  });

  const [search, setSearch] = useState("");
  const [errors, setErrors] = useState({});

  const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value });
    setErrors({ ...errors, [e.target.name]: "" });
  };

  const validate = () => {
    let err = {};
    if (!form.className) err.className = "Required";
    if (!form.section) err.section = "Required";
    if (!form.subjectGroup) err.subjectGroup = "Required";
    if (!form.subject) err.subject = "Required";
    if (!form.lesson) err.lesson = "Required";

    setErrors(err);
    return Object.keys(err).length === 0;
  };

  const handleAdd = () => {
    if (!validate()) return;

    setLessons([{ id: Date.now(), ...form }, ...lessons]);

    setForm({
      className: "",
      section: "",
      subjectGroup: "",
      subject: "",
      lesson: "",
    });
  };

  const handleDelete = (id) => {
    setLessons(lessons.filter((l) => l.id !== id));
  };

  const filtered = useMemo(() => {
    return lessons.filter((l) => {
      const q = search.toLowerCase();
      return (
        l.className.toLowerCase().includes(q) ||
        l.section.toLowerCase().includes(q) ||
        l.subjectGroup.toLowerCase().includes(q) ||
        l.subject.toLowerCase().includes(q) ||
        l.lesson.toLowerCase().includes(q)
      );
    });
  }, [lessons, search]);

  return (
    <>
      <style>{`
        * {
          box-sizing: border-box;
          font-family: Arial, sans-serif;
        }

        body {
          margin: 0;
          background: #f4f6f9;
        }

        .container {
          padding: 20px;
        }

        .card {
          background: #fff;
          padding: 18px;
          border-radius: 10px;
          margin-bottom: 20px;
          border: 1px solid #e5e7eb;
        }

        .title {
          font-size: 20px;
          font-weight: 600;
          margin-bottom: 12px;
          color: #111827;
        }

        .grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
          gap: 12px;
        }

        label {
          font-size: 12px;
          color: #374151;
          margin-bottom: 4px;
          display: block;
        }

        input, select {
          width: 100%;
          padding: 9px;
          border-radius: 6px;
          border: 1px solid #d1d5db;
          outline: none;
          background: #fff;
        }

        input:focus, select:focus {
          border-color: #3b82f6;
        }

        .error {
          font-size: 12px;
          color: red;
          margin-top: 3px;
        }

        .btn {
          margin-top: 12px;
          padding: 10px 16px;
          background: #2563eb;
          color: white;
          border: none;
          border-radius: 6px;
          cursor: pointer;
        }

        .btn:hover {
          background: #1d4ed8;
        }

        .search {
          width: 100%;
          padding: 10px;
          margin-bottom: 12px;
          border: 1px solid #d1d5db;
          border-radius: 6px;
        }

        table {
          width: 100%;
          border-collapse: collapse;
        }

        th {
          text-align: left;
          background: #f9fafb;
          padding: 10px;
          font-size: 13px;
          border-bottom: 1px solid #e5e7eb;
          color: #374151;
        }

        td {
          padding: 10px;
          border-bottom: 1px solid #e5e7eb;
          font-size: 13px;
          color: #111827;
        }

        .badge {
          background: #e0f2fe;
          color: #0369a1;
          padding: 3px 8px;
          border-radius: 12px;
          font-size: 12px;
        }

        .del {
          background: #ef4444;
          color: white;
          border: none;
          padding: 5px 10px;
          border-radius: 6px;
          cursor: pointer;
        }

        .del:hover {
          background: #dc2626;
        }
      `}</style>

      <div className="container">
        {/* ================= ADD LESSON ================= */}
        <div className="card">
          <div className="title">📚 Add Lesson</div>

          <div className="grid">
            <div>
              <label>Class *</label>
              <select
                name="className"
                value={form.className}
                onChange={handleChange}
              >
                <option value="">Select</option>
                {CLASSES.map((c) => (
                  <option key={c}>{c}</option>
                ))}
              </select>
              {errors.className && (
                <div className="error">{errors.className}</div>
              )}
            </div>

            <div>
              <label>Section *</label>
              <select
                name="section"
                value={form.section}
                onChange={handleChange}
              >
                <option value="">Select</option>
                {SECTIONS.map((s) => (
                  <option key={s}>{s}</option>
                ))}
              </select>
              {errors.section && <div className="error">{errors.section}</div>}
            </div>

            <div>
              <label>Subject Group *</label>
              <select
                name="subjectGroup"
                value={form.subjectGroup}
                onChange={handleChange}
              >
                <option value="">Select</option>
                {SUBJECT_GROUPS.map((s) => (
                  <option key={s}>{s}</option>
                ))}
              </select>
              {errors.subjectGroup && (
                <div className="error">{errors.subjectGroup}</div>
              )}
            </div>

            <div>
              <label>Subject *</label>
              <select
                name="subject"
                value={form.subject}
                onChange={handleChange}
              >
                <option value="">Select</option>
                {SUBJECTS.map((s) => (
                  <option key={s}>{s}</option>
                ))}
              </select>
              {errors.subject && <div className="error">{errors.subject}</div>}
            </div>

            <div>
              <label>Lesson Name *</label>
              <input
                name="lesson"
                value={form.lesson}
                onChange={handleChange}
                placeholder="Enter lesson name"
              />
              {errors.lesson && <div className="error">{errors.lesson}</div>}
            </div>
          </div>

          <button className="btn" onClick={handleAdd}>
            + Add Lesson
          </button>
        </div>

        {/* ================= LIST ================= */}
        <div className="card">
          <div className="title">📄 Lesson List</div>

          <input
            className="search"
            placeholder="Search..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />

          <table>
            <thead>
              <tr>
                <th>Class</th>
                <th>Section</th>
                <th>Subject Group</th>
                <th>Subject</th>
                <th>Lesson</th>
                <th>Action</th>
              </tr>
            </thead>

            <tbody>
              {filtered.length === 0 ? (
                <tr>
                  <td
                    colSpan="6"
                    style={{ textAlign: "center", color: "#6b7280" }}
                  >
                    No Data Found
                  </td>
                </tr>
              ) : (
                filtered.map((l) => (
                  <tr key={l.id}>
                    <td>
                      <span className="badge">{l.className}</span>
                    </td>
                    <td>{l.section}</td>
                    <td>{l.subjectGroup}</td>
                    <td>{l.subject}</td>
                    <td>{l.lesson}</td>
                    <td>
                      <button
                        className="del"
                        onClick={() => handleDelete(l.id)}
                      >
                        Delete
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}
