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

export default function AdminSectionViewPage({ sectionId, onBack, onEdit }) {
  const [row, setRow] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = 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);
      setRow(normalizeSectionRow(data));
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
      setRow(null);
    } finally {
      setLoading(false);
    }
  }, [sectionId]);

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

  return (
    <div className="portal-page ptw-mgmt-subpage">
      <MgmtBreadcrumb onBack={onBack} label="Section Management" />
      <PageHeader
        title={row?.title || `Section #${sectionId}`}
        subtitle={row ? `Section #${row.section_id} — read-only overview` : "Loading section…"}
        showBack={false}
        actions={
          onEdit ? (
            <button type="button" className="swi-btn swi-btn--primary" onClick={onEdit} disabled={!row}>
              Edit section
            </button>
          ) : null
        }
      />
      <ErrorBanner message={error} />

      <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 details…</p>
          ) : row ? (
            <SectionDetailView row={row} />
          ) : null}
        </div>
      </div>
    </div>
  );
}
