import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
  deleteSectionQuestionMap,
  getSectionWithQuestions,
  listQuestions,
  mapSectionQuestion
} from "../../../services/formsApi.js";

export default function SectionQuestionsEditor({
  sectionId,
  questions: initialQuestions = [],
  onChanged,
  showAddBar = true
}) {
  const sid = Number(sectionId);
  const [mapped, setMapped] = useState(initialQuestions);
  const [catalog, setCatalog] = useState([]);
  const [selectedIds, setSelectedIds] = useState(() => new Set());
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const reload = useCallback(async () => {
    if (!Number.isFinite(sid) || sid <= 0) {
      setMapped([]);
      return;
    }
    setLoading(true);
    try {
      setError("");
      const data = await getSectionWithQuestions(sid);
      setMapped(Array.isArray(data?.questions) ? data.questions : []);
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setLoading(false);
    }
  }, [sid]);

  useEffect(() => {
    setMapped(Array.isArray(initialQuestions) ? initialQuestions : []);
  }, [sid, initialQuestions]);

  useEffect(() => {
    setSelectedIds(new Set());
  }, [sid]);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const list = await listQuestions();
        if (mounted) setCatalog(Array.isArray(list) ? list : []);
      } catch {
        /* optional */
      }
    })();
    return () => {
      mounted = false;
    };
  }, []);

  const mappedIds = useMemo(
    () => new Set(mapped.map((q) => Number(q.question_id))),
    [mapped]
  );

  const availableQuestions = useMemo(
    () => catalog.filter((q) => !mappedIds.has(Number(q.question_id))),
    [catalog, mappedIds]
  );

  const selectedCount = selectedIds.size;

  function toggleQuestion(questionId) {
    const qid = Number(questionId);
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(qid)) next.delete(qid);
      else next.add(qid);
      return next;
    });
  }

  function selectAllAvailable() {
    setSelectedIds(new Set(availableQuestions.map((q) => Number(q.question_id))));
  }

  function clearSelection() {
    setSelectedIds(new Set());
  }

  async function handleAddSelected() {
    if (!Number.isFinite(sid) || sid <= 0) {
      setError("Invalid section.");
      return;
    }
    const ids = [...selectedIds].filter((id) => Number.isFinite(id) && id > 0);
    if (!ids.length) {
      setError("Select one or more questions to add.");
      return;
    }
    setSaving(true);
    try {
      setError("");
      await Promise.all(
        ids.map((question_id) => mapSectionQuestion({ section_id: sid, question_id }))
      );
      setSelectedIds(new Set());
      await reload();
      await onChanged?.();
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setSaving(false);
    }
  }

  async function handleRemove(questionId) {
    const qid = Number(questionId);
    if (!Number.isFinite(sid) || !Number.isFinite(qid)) return;
    setSaving(true);
    try {
      setError("");
      await deleteSectionQuestionMap(sid, qid);
      await reload();
      await onChanged?.();
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setSaving(false);
    }
  }

  const count = mapped.length;

  return (
    <div className="ptw-section-questions-editor">
      {error ? <p className="ptw-section-questions-editor__error">{error}</p> : null}

      {showAddBar ? (
        <div className="ptw-section-questions-editor__add">
          <div className="ptw-section-questions-editor__add-head">
            <span className="ptw-mgmt-field__label">Add questions to section</span>
            <p className="ptw-section-questions-editor__add-hint">
              Select one or more questions below, then add them in one go.
            </p>
          </div>
          {availableQuestions.length ? (
            <>
              <div className="ptw-section-questions-editor__pick-actions">
                <button
                  type="button"
                  className="swi-btn swi-btn--ghost swi-btn--sm"
                  onClick={selectAllAvailable}
                  disabled={saving || loading}
                >
                  Select all
                </button>
                <button
                  type="button"
                  className="swi-btn swi-btn--ghost swi-btn--sm"
                  onClick={clearSelection}
                  disabled={saving || loading || !selectedCount}
                >
                  Clear selection
                </button>
              </div>
              <div
                className="ptw-section-questions-editor__pick-list"
                role="group"
                aria-label="Questions available to add"
              >
                {availableQuestions.map((q) => {
                  const qid = Number(q.question_id);
                  return (
                    <label key={q.question_id} className="ptw-section-questions-editor__pick-row">
                      <input
                        type="checkbox"
                        checked={selectedIds.has(qid)}
                        onChange={() => toggleQuestion(qid)}
                        disabled={saving || loading}
                      />
                      <span className="ptw-section-questions-editor__pick-text">
                        <span className="ptw-mgmt-tag ptw-mgmt-tag--muted">#{q.question_id}</span>
                        {(q.question || "—").slice(0, 120)}
                        {(q.question || "").length > 120 ? "…" : ""}
                      </span>
                    </label>
                  );
                })}
              </div>
              <button
                type="button"
                className="swi-btn swi-btn--primary ptw-section-questions-editor__add-btn"
                onClick={handleAddSelected}
                disabled={saving || loading || !selectedCount}
              >
                {saving
                  ? "Saving…"
                  : selectedCount
                    ? `Add ${selectedCount} question${selectedCount === 1 ? "" : "s"}`
                    : "Add selected"}
              </button>
            </>
          ) : (
            <p className="ptw-section-questions-editor__pool-empty">
              All questions are already mapped to this section.
            </p>
          )}
        </div>
      ) : null}

      <div className="ptw-section-detail__questions">
        <div className="ptw-section-detail__questions-head">
          <h4 className="ptw-section-detail__questions-title">Mapped questions</h4>
          <span className="ptw-section-detail__questions-count">
            {loading ? "…" : `${count} ${count === 1 ? "item" : "items"}`}
          </span>
        </div>
        {loading && !mapped.length ? (
          <div className="ptw-section-detail__empty">
            <p>Loading questions…</p>
          </div>
        ) : mapped.length ? (
          <ol className="ptw-section-detail__question-list">
            {mapped.map((q, index) => {
              const options = Array.isArray(q.options) ? q.options : [];
              const optionLabels = options
                .map((o) => (typeof o === "string" ? o : o.option ?? o._options ?? ""))
                .filter(Boolean);
              return (
                <li key={q.question_id} className="ptw-section-detail__question-item">
                  <span className="ptw-section-detail__question-index">{index + 1}</span>
                  <div className="ptw-section-detail__question-body">
                    <div className="ptw-section-detail__question-head">
                      <span className="ptw-mgmt-tag ptw-mgmt-tag--muted">#{q.question_id}</span>
                      {q.question_type ? (
                        <span className="ptw-mgmt-tag">{q.question_type}</span>
                      ) : null}
                      {q.allows_media ? (
                        <span className="ptw-mgmt-tag ptw-mgmt-tag--muted">Media</span>
                      ) : null}
                      <button
                        type="button"
                        className="ptw-mgmt-btn ptw-section-questions-editor__remove"
                        disabled={saving || loading}
                        onClick={() => handleRemove(q.question_id)}
                      >
                        Remove
                      </button>
                    </div>
                    <p className="ptw-section-detail__question-text">{q.question || "—"}</p>
                    {optionLabels.length ? (
                      <div className="ptw-section-detail__options">
                        <span className="ptw-section-detail__options-label">Options</span>
                        <ul className="ptw-section-detail__options-list">
                          {optionLabels.map((label, i) => (
                            <li key={i}>{label}</li>
                          ))}
                        </ul>
                      </div>
                    ) : null}
                  </div>
                </li>
              );
            })}
          </ol>
        ) : (
          <div className="ptw-section-detail__empty">
            <p>No questions mapped yet.</p>
            <span>Use the checkboxes above to add questions to this section.</span>
          </div>
        )}
      </div>
    </div>
  );
}
