"use client";

import { useEffect, useRef, useState } from "react";
import { toast } from "react-toastify";
import CustomLoader from "@/components/common/CustomLoader";

interface ClassLevelItem {
  id: string;
  title: string;
  age: string | null;
  duration: string | null;
  prerequisite: string | null;
  description: string | null;
  points: string | null; // newline-separated
  sort_order: number;
  status: boolean;
  isNew?: boolean; // client-only flag for unsaved new rows
}

const emptyItem = (sort_order: number): ClassLevelItem => ({
  id: `new-${Date.now()}`,
  title: "",
  age: "",
  duration: "",
  prerequisite: "",
  description: "",
  points: "",
  sort_order,
  status: true,
  isNew: true,
});

export default function ClassLevelsPage() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [items, setItems] = useState<ClassLevelItem[]>([]);
  const cardRefs = useRef<Record<string, HTMLDivElement | null>>({});

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      setLoading(true);

      const res = await fetch("/api/admin/cms/class-levels");
      const json = await res.json();

      if (json.success) {
        setItems(json.data);
      } else {
        toast.error(json.message || "Failed to load data");
      }
    } catch {
      toast.error("Failed to load data");
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (index: number, field: string, value: any) => {
    const updated = [...items];
    updated[index] = { ...updated[index], [field]: value };
    setItems(updated);
  };

  const scrollToCard = (id: string) => {
    setTimeout(() => {
      cardRefs.current[id]?.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 50);
  };

  const handleAddCard = () => {
    const newItem = emptyItem(items.length);
    setItems([...items, newItem]);
    scrollToCard(newItem.id);
  };

  const handleDeleteCard = async (index: number) => {
    const item = items[index];

    if (item.isNew) {
      // never saved, just remove from local state
      setItems(items.filter((_, i) => i !== index));
      delete cardRefs.current[item.id];
      return;
    }

    if (!confirm(`Delete "${item.title}"? This cannot be undone.`)) return;

    try {
      const res = await fetch(
        `/api/admin/cms/class-levels?id=${item.id}`,
        { method: "DELETE" }
      );
      const json = await res.json();

      if (json.success) {
        setItems(items.filter((_, i) => i !== index));
        delete cardRefs.current[item.id];
        toast.success("Class level deleted");
      } else {
        toast.error(json.message || "Failed to delete");
      }
    } catch {
      toast.error("Failed to delete");
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);

      for (const item of items) {
        const payload = {
          id: item.isNew ? undefined : item.id,
          title: item.title,
          age: item.age,
          duration: item.duration,
          prerequisite: item.prerequisite,
          description: item.description,
          points: item.points,
          sort_order: item.sort_order,
          status: item.status,
        };

        if (item.isNew) {
          await fetch("/api/admin/cms/class-levels", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
          });
        } else {
          await fetch("/api/admin/cms/class-levels", {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
          });
        }
      }

      toast.success("Class Levels updated successfully");
      fetchData();
    } catch {
      toast.error("Failed to save changes");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return <CustomLoader />;
  }

  return (
    <div className="admin-page-wrapper">
      <div className="admin-page-header mb-4">
        <div className="d-flex justify-content-between align-items-center">
          <div>
            <h2 className="admin-page-title">Class Level</h2>
            <p className="admin-page-subtitle">
              Manage Academy &raquo; Class Level section
            </p>
          </div>

          <div className="d-flex gap-2">
            <button className="admin-theme-btn" onClick={handleAddCard}>
              <i className="bi bi-plus-lg me-2" />
              Add Card
            </button>

            <button
              className="admin-theme-btn"
              onClick={handleSave}
              disabled={saving}
            >
              {saving ? (
                <>
                  <span className="spinner-border spinner-border-sm me-2" />
                  Saving...
                </>
              ) : (
                <>
                  <i className="bi bi-floppy me-2" />
                  Save Changes
                </>
              )}
            </button>
          </div>
        </div>
      </div>

      <div className="row">
        {items.map((item, index) => (
          <div className="col-lg-12" key={item.id}>
            <div
              className="card-theme p-3 p-md-3 h-100"
              ref={(el) => {
                cardRefs.current[item.id] = el;
              }}
            >
              <div className="d-flex justify-content-between align-items-center mb-3">
                <h5 className="mb-0 fw-semibold">
                  <i className="bi bi-mortarboard me-2 text-primary" />
                  {item.title || `Card ${index + 1}`}
                </h5>

                <button
                  className="btn btn-sm btn-outline-danger"
                  onClick={() => handleDeleteCard(index)}
                  title="Delete this card"
                >
                  <i className="bi bi-trash" />
                </button>
              </div>

              <div className="row g-3">
                <div className="col-6">
                  <label className="form-label">Title</label>
                  <input
                    type="text"
                    className="form-control"
                    value={item.title}
                    onChange={(e) =>
                      handleChange(index, "title", e.target.value)
                    }
                  />
                </div>

                <div className="col-md-4 d-flex align-items-center">
                  <div className="form-check form-switch mt-4">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      checked={item.status}
                      onChange={(e) =>
                        handleChange(index, "status", e.target.checked)
                      }
                    />
                    <label className="form-check-label">Active</label>
                  </div>
                </div>

                <div className="col-6">
                  <label className="form-label">Minimum Age</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="e.g. 6-7 YRS"
                    value={item.age || ""}
                    onChange={(e) =>
                      handleChange(index, "age", e.target.value)
                    }
                  />
                </div>

                <div className="col-6">
                  <label className="form-label">Duration</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="e.g. 60-MINUTE CLASS"
                    value={item.duration || ""}
                    onChange={(e) =>
                      handleChange(index, "duration", e.target.value)
                    }
                  />
                </div>

                <div className="col-12">
                  <label className="form-label">Pre-requisite</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="Leave blank if none"
                    value={item.prerequisite || ""}
                    onChange={(e) =>
                      handleChange(index, "prerequisite", e.target.value)
                    }
                  />
                </div>

                <div className="col-12">
                  <label className="form-label">Description</label>
                  <textarea
                    rows={2}
                    className="form-control"
                    value={item.description || ""}
                    onChange={(e) =>
                      handleChange(index, "description", e.target.value)
                    }
                  />
                </div>

                <div className="col-12">
                  <label className="form-label">
                    Students will learn (one per line)
                  </label>
                  <textarea
                    rows={5}
                    className="form-control"
                    placeholder={"Basic Posture\nWarm up exercises\n..."}
                    value={item.points || ""}
                    onChange={(e) =>
                      handleChange(index, "points", e.target.value)
                    }
                  />
                </div>

                <div className="col-4">
                  <label className="form-label">Sort Order</label>
                  <input
                    type="number"
                    className="form-control"
                    value={item.sort_order}
                    onChange={(e) =>
                      handleChange(
                        index,
                        "sort_order",
                        Number(e.target.value)
                      )
                    }
                    min={0}
                  />
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-4 text-end">
        <button
          className="admin-theme-btn"
          onClick={handleSave}
          disabled={saving}
        >
          {saving ? (
            <>
              <span className="spinner-border spinner-border-sm me-2" />
              Saving...
            </>
          ) : (
            <>
              <i className="bi bi-floppy me-2" />
              Save Changes
            </>
          )}
        </button>
      </div>
    </div>
  );
}