import React, { useCallback, useEffect, useState } from "react";
import ErrorBanner from "../../../components/common/ErrorBanner.jsx";
import { getSectionWithQuestions, listSections } from "../../../services/formsApi.js";
import SectionQuestionsEditor from "./SectionQuestionsEditor.jsx";

export default function SectionQuestionMapPanel({ onMapChanged }) {
  const [sections, setSections] = useState([]);
  const [sectionId, setSectionId] = useState("");
  const [sectionTitle, setSectionTitle] = useState("");
  const [mapped, setMapped] = useState([]);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const loadCatalog = useCallback(async () => {
    try {
      const sec = await listSections();
      setSections(Array.isArray(sec) ? sec : []);
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    }
  }, []);

  const loadMapped = useCallback(async (id) => {
    if (!id) {
      setMapped([]);
      setSectionTitle("");
      return;
    }
    setLoading(true);
    try {
      setError("");
      const data = await getSectionWithQuestions(id);
      setSectionTitle(data?.title || `Section #${id}`);
      setMapped(Array.isArray(data?.questions) ? data.questions : []);
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
      setMapped([]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  useEffect(() => {
    if (sectionId) {
      loadMapped(sectionId);
    }
  }, [sectionId, loadMapped]);

  async function handleChanged() {
    await loadMapped(sectionId);
    await onMapChanged?.();
  }

  return (
    <div className="ptw-mgmt-card">
      <div className="ptw-mgmt-card__header">
        <div>
          <h2 className="ptw-mgmt-card__title">Map questions to existing sections</h2>
          <p className="ptw-mgmt-card__desc">
            Select a section, then add or remove questions. For new sections, use{" "}
            <strong>Create Section</strong> to map questions before saving.
          </p>
        </div>
      </div>

      <ErrorBanner message={error} />

      <div className="ptw-mgmt-form-grid ptw-map-toolbar">
        <label className="ptw-mgmt-field ptw-mgmt-field--span2">
          <span className="ptw-mgmt-field__label">Section</span>
          <select
            className="ptw-mgmt-input ptw-mgmt-select"
            value={sectionId}
            onChange={(e) => setSectionId(e.target.value)}
          >
            <option value="">Select section</option>
            {sections.map((s) => (
              <option key={s.section_id} value={String(s.section_id)}>
                #{s.section_id} — {s.title || "Untitled"}
              </option>
            ))}
          </select>
        </label>
      </div>

      {sectionId ? (
        <>
          <div className="ptw-mgmt-list-meta">
            <span>
              {loading
                ? "Loading mapped questions…"
                : `Managing questions for "${sectionTitle}"`}
            </span>
            <button
              type="button"
              className="swi-btn swi-btn--ghost"
              onClick={() => loadMapped(sectionId)}
              disabled={loading}
            >
              Refresh
            </button>
          </div>
          <SectionQuestionsEditor
            sectionId={sectionId}
            questions={mapped}
            onChanged={handleChanged}
          />
        </>
      ) : (
        <p className="ptw-muted ptw-mgmt-list-loading">
          Select a section to add or remove its questions.
        </p>
      )}
    </div>
  );
}
