import React, { useEffect, useState } from "react";
import PtwMgmtPage from "../../components/admin/PtwMgmtPage.jsx";
import SectionCreatePanel from "./components/SectionCreatePanel.jsx";
import SectionQuestionMapPanel from "./components/SectionQuestionMapPanel.jsx";
import AdminSectionViewPage from "./section/AdminSectionViewPage.jsx";
import AdminSectionUpdatePage from "./section/AdminSectionUpdatePage.jsx";
import {
  blankSection,
  buildSectionPayload,
  draftFromRow,
  normalizeSectionRow,
  SectionFields
} from "./section/sectionMgmtShared.jsx";
import {
  listFormSectionMaps,
  listForms,
  listSectionQuestionMaps,
  listSections,
  updateSection
} from "../../services/formsApi.js";
import { formatMgmtDate, mgmtActionColumn } from "../../utils/ptwMgmtHelpers.jsx";

export default function AdminSectionManagementPage() {
  const [route, setRoute] = useState(null);
  const [questionCountBySection, setQuestionCountBySection] = useState({});
  const [formCountBySection, setFormCountBySection] = useState({});
  const [formOptions, setFormOptions] = useState([]);
  const [mapRefreshKey, setMapRefreshKey] = useState(0);
  const [listRefreshKey, setListRefreshKey] = useState(0);

  const refreshCounts = async () => {
    try {
      const [qMaps, fMaps, forms] = await Promise.all([
        listSectionQuestionMaps(),
        listFormSectionMaps(),
        listForms()
      ]);
      const qCounts = {};
      for (const row of qMaps) {
        const sid = Number(row.section_id);
        if (Number.isFinite(sid)) qCounts[sid] = (qCounts[sid] || 0) + 1;
      }
      const fCounts = {};
      for (const row of fMaps) {
        const sid = Number(row.section_id);
        if (Number.isFinite(sid)) fCounts[sid] = (fCounts[sid] || 0) + 1;
      }
      setQuestionCountBySection(qCounts);
      setFormCountBySection(fCounts);
      setFormOptions(
        (Array.isArray(forms) ? forms : []).map((f) => ({
          value: String(f.form_id),
          label: `#${f.form_id} — ${f.title || "Untitled"}`
        }))
      );
      setMapRefreshKey((k) => k + 1);
      setListRefreshKey((k) => k + 1);
    } catch {
      /* optional */
    }
  };

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

  if (route?.screen === "view") {
    return (
      <AdminSectionViewPage
        sectionId={route.sectionId}
        onBack={() => setRoute(null)}
        onEdit={() => setRoute({ screen: "update", sectionId: route.sectionId })}
      />
    );
  }

  if (route?.screen === "update") {
    return (
      <AdminSectionUpdatePage
        sectionId={route.sectionId}
        onBack={() => setRoute(null)}
        onSaved={refreshCounts}
        onQuestionsChanged={refreshCounts}
      />
    );
  }

  return (
    <PtwMgmtPage
      key={listRefreshKey}
      title="Section Management"
      subtitle="Create sections with questions, or open View / Update from the list for full-page section management."
      keyField="section_id"
      labels={{
        createTab: "Create Section",
        listTab: "View All Sections",
        createHeading: "Create a new section",
        createDesc: "",
        createSectionTitle: "Section details",
        listHeading: "All sections",
        listDesc: "Use View for details or Update to edit metadata and manage questions.",
        entitySingular: "section",
        entityPlural: "sections",
        createButton: "Create section",
        createSaving: "Creating…",
        clearButton: "Clear form",
        createSuccess: "Section has been created with mapped questions.",
        updateSuccess: "Section update has been completed.",
        emptyList: "No sections yet. Use Create Section to add your first section.",
        viewModalTitle: "View section",
        updateModalTitle: "Update section",
        viewLoading: "Loading section details…"
      }}
      blankDraft={blankSection}
      buildPayload={buildSectionPayload}
      draftFromRow={draftFromRow}
      normalizeRow={normalizeSectionRow}
      listFn={listSections}
      createFn={async () => ({})}
      updateFn={updateSection}
      validateDraft={(draft) => (draft.title?.trim() ? null : "Title is required.")}
      onViewRow={(row) =>
        setRoute({ screen: "view", sectionId: Number(row.section_id) })
      }
      onUpdateRow={(row) =>
        setRoute({ screen: "update", sectionId: Number(row.section_id) })
      }
      replaceCreatePanel={({ onComplete }) => (
        <SectionCreatePanel
          formOptions={formOptions}
          onComplete={async () => {
            await refreshCounts();
            await onComplete();
          }}
        />
      )}
      renderFields={({ draft, setDraft }) => (
        <SectionFields draft={draft} setDraft={setDraft} />
      )}
      buildColumns={({ openView, openUpdate }) => [
        { key: "section_id", label: "ID" },
        { key: "title", label: "Title" },
        { key: "section_parent_id", label: "Parent" },
        {
          key: "form_count",
          label: "Forms",
          render: (r) => (
            <span className="ptw-mgmt-tag ptw-mgmt-tag--muted">
              {formCountBySection[r.section_id] ?? 0}
            </span>
          )
        },
        {
          key: "question_count",
          label: "Questions",
          render: (r) => (
            <span className="ptw-mgmt-tag">
              {questionCountBySection[r.section_id] ?? 0}
            </span>
          )
        },
        { key: "created_by", label: "Created by" },
        {
          key: "created_date",
          label: "Created",
          render: (r) => formatMgmtDate(r.created_date)
        },
        mgmtActionColumn({ openView, openUpdate })
      ]}
      extraTabs={[
        {
          id: "map",
          label: "Map Questions (existing)",
          render: () => (
            <SectionQuestionMapPanel
              key={mapRefreshKey}
              onMapChanged={refreshCounts}
            />
          )
        }
      ]}
    />
  );
}
