import React, { useEffect, useMemo, useState } from "react";
import DataTable from "../../../components/common/DataTable.jsx";
import ErrorBanner from "../../../components/common/ErrorBanner.jsx";
import {
  createSection,
  listQuestions,
  mapFormSection,
  mapSectionQuestion
} from "../../../services/formsApi.js";

const blankSection = {
  title: "",
  section_parent_id: "",
  created_by: "",
  form_id: "",
  section_in_form_order: ""
};

export default function SectionCreatePanel({ formOptions = [], onComplete }) {
  const [draft, setDraft] = useState(blankSection);
  const [allQuestions, setAllQuestions] = useState([]);
  const [pendingQuestions, setPendingQuestions] = useState([]);
  const [selectedIds, setSelectedIds] = useState(() => new Set());
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const q = await listQuestions();
        if (mounted) setAllQuestions(Array.isArray(q) ? q : []);
      } catch (err) {
        if (mounted) setError(err?.response?.data?.message || err.message);
      }
    })();
    return () => {
      mounted = false;
    };
  }, []);

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

  const availableToAdd = useMemo(
    () => allQuestions.filter((q) => !pendingIds.has(Number(q.question_id))),
    [allQuestions, pendingIds]
  );

  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(availableToAdd.map((q) => Number(q.question_id))));
  }

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

  const addSelectedQuestions = () => {
    const ids = [...selectedIds].filter((id) => Number.isFinite(id) && id > 0);
    if (!ids.length) {
      setError("Select one or more questions to add to this section.");
      return;
    }
    const rows = ids
      .map((id) => allQuestions.find((q) => Number(q.question_id) === id))
      .filter(Boolean);
    if (!rows.length) return;
    setPendingQuestions((prev) => {
      const existing = new Set(prev.map((q) => Number(q.question_id)));
      return [...prev, ...rows.filter((q) => !existing.has(Number(q.question_id)))];
    });
    setSelectedIds(new Set());
    setError("");
  };

  const removeQuestion = (questionId) => {
    setPendingQuestions((prev) =>
      prev.filter((q) => Number(q.question_id) !== Number(questionId))
    );
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!draft.title?.trim()) {
      setError("Section title is required.");
      return;
    }
    if (pendingQuestions.length === 0) {
      setError("Add at least one question before creating the section.");
      return;
    }

    setSaving(true);
    setError("");
    try {
      const sectionPayload = { title: draft.title.trim() };
      if (draft.section_parent_id) {
        sectionPayload.section_parent_id = Number(draft.section_parent_id);
      }
      if (draft.created_by) sectionPayload.created_by = Number(draft.created_by);

      const created = await createSection(sectionPayload);
      const sectionId = created?.insertedId ?? created?.section_id;
      if (!sectionId) {
        throw new Error("Section was created but no section id was returned.");
      }

      await Promise.all(
        pendingQuestions.map((q) =>
          mapSectionQuestion({
            section_id: Number(sectionId),
            question_id: Number(q.question_id)
          })
        )
      );

      if (draft.form_id) {
        const mapPayload = {
          form_id: Number(draft.form_id),
          section_id: Number(sectionId)
        };
        if (draft.section_in_form_order !== "" && draft.section_in_form_order != null) {
          mapPayload.section_in_form_order = Number(draft.section_in_form_order);
        }
        await mapFormSection(mapPayload);
      }

      setDraft(blankSection);
      setPendingQuestions([]);
      setSelectedIds(new Set());
      if (onComplete) await onComplete();
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setSaving(false);
    }
  };

  const columns = useMemo(
    () => [
      { key: "question_id", label: "ID" },
      {
        key: "question",
        label: "Question",
        render: (r) => (
          <span className="ptw-mgmt-cell-clip">{r.question || "—"}</span>
        )
      },
      {
        key: "actions",
        label: "",
        render: (r) => (
          <button
            type="button"
            className="ptw-mgmt-btn ptw-mgmt-btn--edit"
            onClick={() => removeQuestion(r.question_id)}
            disabled={saving}
          >
            Remove
          </button>
        )
      }
    ],
    [saving]
  );

  return (
    <form className="ptw-mgmt-card" onSubmit={handleSubmit}>
      <div className="ptw-mgmt-card__header">
        <div>
          <h2 className="ptw-mgmt-card__title">Create a new section</h2>
          <p className="ptw-mgmt-card__desc">
            Add questions to the section first. The section is created only when you save,
            with all mappings written to <code>ptw_section_question_map</code>.
          </p>
        </div>
      </div>

      <ErrorBanner message={error} />

      <div className="ptw-mgmt-section">
        <h3 className="ptw-mgmt-section__title">1. Section details</h3>
        <div className="ptw-mgmt-form-grid">
          <label className="ptw-mgmt-field ptw-mgmt-field--span2">
            <span className="ptw-mgmt-field__label">
              Section title <em className="ptw-mgmt-required">*</em>
            </span>
            <input
              className="ptw-mgmt-input"
              value={draft.title}
              onChange={(e) => setDraft((prev) => ({ ...prev, title: e.target.value }))}
              placeholder="e.g. Safety checklist"
            />
          </label>
          <label className="ptw-mgmt-field">
            <span className="ptw-mgmt-field__label">Parent section ID</span>
            <input
              className="ptw-mgmt-input"
              type="number"
              min="1"
              value={draft.section_parent_id}
              onChange={(e) =>
                setDraft((prev) => ({ ...prev, section_parent_id: e.target.value }))
              }
              placeholder="Optional"
            />
          </label>
          <label className="ptw-mgmt-field">
            <span className="ptw-mgmt-field__label">Created by (user ID)</span>
            <input
              className="ptw-mgmt-input"
              type="number"
              min="1"
              value={draft.created_by}
              onChange={(e) => setDraft((prev) => ({ ...prev, created_by: e.target.value }))}
              placeholder="Optional"
            />
          </label>
          <label className="ptw-mgmt-field">
            <span className="ptw-mgmt-field__label">Link to form (optional)</span>
            <select
              className="ptw-mgmt-input ptw-mgmt-select"
              value={draft.form_id}
              onChange={(e) => setDraft((prev) => ({ ...prev, form_id: e.target.value }))}
            >
              <option value="">No form</option>
              {formOptions.map((opt) => (
                <option key={opt.value} value={opt.value}>{opt.label}</option>
              ))}
            </select>
          </label>
          <label className="ptw-mgmt-field">
            <span className="ptw-mgmt-field__label">Order in form (optional)</span>
            <input
              className="ptw-mgmt-input"
              type="number"
              min="0"
              value={draft.section_in_form_order}
              onChange={(e) =>
                setDraft((prev) => ({ ...prev, section_in_form_order: e.target.value }))
              }
              placeholder="Auto if empty"
              disabled={!draft.form_id}
            />
          </label>
        </div>
      </div>

      <div className="ptw-mgmt-section">
        <h3 className="ptw-mgmt-section__title">
          2. Map questions <em className="ptw-mgmt-required">*</em>
        </h3>
        <p className="ptw-mgmt-card__desc" style={{ marginTop: 0 }}>
          Select one or more questions below and add them to the section. They are saved when you create
          the section.
        </p>

        {availableToAdd.length ? (
          <div className="ptw-section-questions-editor__add">
            <div className="ptw-section-questions-editor__pick-actions">
              <button
                type="button"
                className="swi-btn swi-btn--ghost swi-btn--sm"
                onClick={selectAllAvailable}
                disabled={saving}
              >
                Select all
              </button>
              <button
                type="button"
                className="swi-btn swi-btn--ghost swi-btn--sm"
                onClick={clearSelection}
                disabled={saving || !selectedIds.size}
              >
                Clear selection
              </button>
            </div>
            <div
              className="ptw-section-questions-editor__pick-list"
              role="group"
              aria-label="Questions to map to this section"
            >
              {availableToAdd.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}
                    />
                    <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--ghost ptw-section-questions-editor__add-btn"
              onClick={addSelectedQuestions}
              disabled={saving || !selectedIds.size}
            >
              {selectedIds.size
                ? `Add ${selectedIds.size} to section list`
                : "Add selected to section list"}
            </button>
          </div>
        ) : (
          <p className="ptw-section-questions-editor__pool-empty">
            {allQuestions.length
              ? "All available questions are already in the section list."
              : "No questions in the bank yet. Create questions first."}
          </p>
        )}

        <div className="ptw-mgmt-list-meta">
          <span>
            {pendingQuestions.length} question
            {pendingQuestions.length === 1 ? "" : "s"} ready to map
          </span>
        </div>

        <DataTable
          columns={columns}
          rows={pendingQuestions}
          keyField="question_id"
          emptyMessage="No questions added yet. Add at least one question before creating the section."
        />
      </div>

      <div className="ptw-mgmt-card__footer">
        <button
          type="submit"
          className="swi-btn swi-btn--primary"
          disabled={saving || pendingQuestions.length === 0}
        >
          {saving ? "Creating section…" : "Create section with mapped questions"}
        </button>
        <button
          type="button"
          className="swi-btn swi-btn--ghost"
          onClick={() => {
            setDraft(blankSection);
            setPendingQuestions([]);
            setSelectedIds(new Set());
            setError("");
          }}
          disabled={saving}
        >
          Clear
        </button>
      </div>
    </form>
  );
}
