import React, { useCallback, useEffect, useState } from "react";
import PageHeader from "../../../components/common/PageHeader.jsx";
import ErrorBanner from "../../../components/common/ErrorBanner.jsx";
import SectionQuestionsEditor from "../components/SectionQuestionsEditor.jsx";
import { getSectionWithQuestions, updateSection } from "../../../services/formsApi.js";
import {
  MgmtBreadcrumb,
  SectionFields,
  buildSectionPayload,
  draftFromRow,
  normalizeSectionRow
} from "./sectionMgmtShared.jsx";

export default function AdminSectionUpdatePage({
  sectionId,
  onBack,
  onSaved,
  onQuestionsChanged
}) {
  const [row, setRow] = useState(null);
  const [draft, setDraft] = useState({ title: "", section_parent_id: "", created_by: "" });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const load = useCallback(async () => {
    const id = Number(sectionId);
    if (!Number.isFinite(id) || id <= 0) {
      setError("Invalid section id.");
      setLoading(false);
      return;
    }
    setLoading(true);
    try {
      setError("");
      const data = await getSectionWithQuestions(id);
      const normalized = normalizeSectionRow(data);
      setRow(normalized);
      setDraft(draftFromRow(normalized));
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
      setRow(null);
    } finally {
      setLoading(false);
    }
  }, [sectionId]);

  useEffect(() => {
    load();
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, [load]);

  async function handleSave() {
    if (!row) return;
    if (!draft.title?.trim()) {
      setError("Title is required.");
      return;
    }
    const id = Number(row.section_id);
    setSaving(true);
    setSuccess("");
    try {
      setError("");
      await updateSection(id, buildSectionPayload(draft));
      setSuccess("Section details saved.");
      await load();
      await onSaved?.();
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="portal-page ptw-mgmt-subpage">
      <MgmtBreadcrumb onBack={onBack} label="Section Management" />
      <PageHeader
        title={row?.title ? `Edit: ${row.title}` : `Edit section #${sectionId}`}
        subtitle="Update section metadata and manage mapped questions."
        showBack={false}
      />
      <ErrorBanner message={error} />
      {success ? <p className="ptw-mgmt-success-banner">{success}</p> : null}

      <div className="ptw-mgmt-shell ptw-mgmt-subpage__card">
        <div className="ptw-mgmt-body">
          {loading ? (
            <p className="ptw-muted ptw-mgmt-list-loading">Loading section…</p>
          ) : row ? (
            <>
              <section className="ptw-mgmt-section">
                <h2 className="ptw-mgmt-section__title">Section details</h2>
                <SectionFields draft={draft} setDraft={setDraft} />
                <div className="ptw-mgmt-card__footer">
                  <button
                    type="button"
                    className="swi-btn swi-btn--primary"
                    onClick={handleSave}
                    disabled={saving}
                  >
                    {saving ? "Saving…" : "Save section details"}
                  </button>
                  <button type="button" className="swi-btn swi-btn--ghost" onClick={onBack}>
                    Cancel
                  </button>
                </div>
              </section>

              <section className="ptw-section-update-questions ptw-section-update-questions--page">
                <h2 className="ptw-mgmt-section__title">Section questions</h2>
                <p className="ptw-muted ptw-section-update-questions__hint">
                  Add or remove question mappings. Each change is saved immediately.
                </p>
                <SectionQuestionsEditor
                  sectionId={row.section_id}
                  questions={row.questions || []}
                  onChanged={async () => {
                    await load();
                    await onQuestionsChanged?.();
                  }}
                />
              </section>
            </>
          ) : null}
        </div>
      </div>
    </div>
  );
}
