import React, { useCallback, useEffect, useMemo, useState } from "react";
import PageHeader from "../../components/common/PageHeader.jsx";
import DataTable from "../../components/common/DataTable.jsx";
import ErrorBanner from "../../components/common/ErrorBanner.jsx";
import EntityModal from "../../components/common/EntityModal.jsx";
import useMasterData from "../../hooks/useMasterData.js";
import {
  createForm,
  getForm,
  listFormSectionMaps,
  listForms,
  updateForm
} from "../../services/formsApi.js";
import FormSectionMapPanel from "./components/FormSectionMapPanel.jsx";
import NestedFormPublishPanel from "./components/NestedFormPublishPanel.jsx";

const TABS = { CREATE: "create", LIST: "list", MAP_SECTIONS: "map-sections" };

const blankForm = {
  title: "",
  description: "",
  form_type_id: "",
  job_type_id: "",
  created_by: ""
};

function buildFormPayload(draft) {
  const payload = {};
  if (draft.title?.trim()) payload.title = draft.title.trim();
  if (draft.description?.trim()) payload.description = draft.description.trim();
  if (draft.form_type_id) payload.form_type_id = Number(draft.form_type_id);
  if (draft.job_type_id) payload.job_type_id = Number(draft.job_type_id);
  if (draft.created_by) payload.created_by = Number(draft.created_by);
  return payload;
}

function draftFromRow(row) {
  return {
    title: row.title ?? "",
    description: row.description ?? "",
    form_type_id: row.form_type_id != null ? String(row.form_type_id) : "",
    job_type_id: row.job_type_id != null ? String(row.job_type_id) : "",
    created_by: row.created_by != null ? String(row.created_by) : ""
  };
}

function normalizeFormRow(row) {
  if (!row || typeof row !== "object") return null;
  const formId = Number(row.form_id);
  return {
    ...row,
    form_id: Number.isFinite(formId) ? formId : row.form_id,
    form_type_id:
      row.form_type_id != null && row.form_type_id !== ""
        ? Number(row.form_type_id)
        : null,
    job_type_id:
      row.job_type_id != null && row.job_type_id !== ""
        ? Number(row.job_type_id)
        : null,
    created_by:
      row.created_by != null && row.created_by !== ""
        ? Number(row.created_by)
        : null
  };
}

function formatFormDate(value) {
  if (!value) return "—";
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? "—" : d.toLocaleDateString();
}

function formatFormDateTime(value) {
  if (!value) return "—";
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? "—" : d.toLocaleString();
}

function FormFields({ draft, setDraft, formTypeOptions, jobTypeOptions }) {
  return (
    <div className="ptw-mgmt-form-grid">
      <label className="ptw-mgmt-field ptw-mgmt-field--span2">
        <span className="ptw-mgmt-field__label">Form 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. Hot Work Permit Checklist"
        />
      </label>
      <label className="ptw-mgmt-field">
        <span className="ptw-mgmt-field__label">Form type</span>
        <select
          className="ptw-mgmt-input ptw-mgmt-select"
          value={draft.form_type_id}
          onChange={(e) => setDraft((prev) => ({ ...prev, form_type_id: e.target.value }))}
        >
          <option value="">Select form type</option>
          {formTypeOptions.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">Job type</span>
        <select
          className="ptw-mgmt-input ptw-mgmt-select"
          value={draft.job_type_id}
          onChange={(e) => setDraft((prev) => ({ ...prev, job_type_id: e.target.value }))}
        >
          <option value="">Select job type</option>
          {jobTypeOptions.map((opt) => (
            <option key={opt.value} value={opt.value}>{opt.label}</option>
          ))}
        </select>
        <p className="ptw-mgmt-type-format__hint">
          Need a new job type? Add it in{" "}
          <a href="#/job-type-management">Job Type Management</a>, then refresh this page.
        </p>
      </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 ptw-mgmt-field--full">
        <span className="ptw-mgmt-field__label">Description</span>
        <textarea
          className="ptw-mgmt-input ptw-mgmt-textarea"
          rows={4}
          value={draft.description}
          onChange={(e) => setDraft((prev) => ({ ...prev, description: e.target.value }))}
          placeholder="Brief description of this form and when it should be used"
        />
      </label>
    </div>
  );
}

function FormDetailView({ form, formTypeName, jobTypeName, sectionCount }) {
  return (
    <dl className="ptw-key-value ptw-mgmt-detail">
      <dt>Form ID</dt>
      <dd>{form.form_id}</dd>
      <dt>Title</dt>
      <dd>{form.title || "—"}</dd>
      <dt>Mapped sections</dt>
      <dd>{sectionCount ?? 0}</dd>
      <dt>Description</dt>
      <dd>{form.description || "—"}</dd>
      <dt>Form type</dt>
      <dd>{formTypeName[String(form.form_type_id)] || form.form_type_id || "—"}</dd>
      <dt>Job type</dt>
      <dd>{jobTypeName[String(form.job_type_id)] || form.job_type_id || "—"}</dd>
      <dt>Created by</dt>
      <dd>{form.created_by ?? "—"}</dd>
      <dt>Created</dt>
      <dd>{formatFormDateTime(form.created_date)}</dd>
    </dl>
  );
}

export default function AdminFormManagementPage() {
  const { data } = useMasterData();
  const [activeTab, setActiveTab] = useState(TABS.CREATE);
  const [rows, setRows] = useState([]);
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);
  const [createDraft, setCreateDraft] = useState(blankForm);
  const [viewForm, setViewForm] = useState(null);
  const [updateFormRow, setUpdateFormRow] = useState(null);
  const [editDraft, setEditDraft] = useState(blankForm);
  const [successPopup, setSuccessPopup] = useState(null);
  const [listLoading, setListLoading] = useState(false);
  const [viewLoading, setViewLoading] = useState(false);
  const [sectionCountByForm, setSectionCountByForm] = useState({});

  const formTypeOptions = useMemo(
    () => (data.ptw_form_type || []).map((row) => ({
      value: String(row.form_type_id),
      label: row.form_type_name || `#${row.form_type_id}`
    })),
    [data.ptw_form_type]
  );
  const jobTypeOptions = useMemo(
    () => (data.ptw_job_type || []).map((row) => ({
      value: String(row.job_type_id),
      label: row.job_type_name || `#${row.job_type_id}`
    })),
    [data.ptw_job_type]
  );

  const formTypeName = useMemo(
    () => Object.fromEntries(formTypeOptions.map((o) => [o.value, o.label])),
    [formTypeOptions]
  );
  const jobTypeName = useMemo(
    () => Object.fromEntries(jobTypeOptions.map((o) => [o.value, o.label])),
    [jobTypeOptions]
  );

  async function loadForms() {
    setListLoading(true);
    try {
      setError("");
      const list = await listForms();
      const normalized = (Array.isArray(list) ? list : [])
        .map(normalizeFormRow)
        .filter(Boolean);
      setRows(normalized);
      return normalized;
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
      return null;
    } finally {
      setListLoading(false);
    }
  }

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

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const maps = await listFormSectionMaps();
        const counts = {};
        for (const row of maps) {
          const fid = Number(row.form_id);
          if (Number.isFinite(fid)) {
            counts[fid] = (counts[fid] || 0) + 1;
          }
        }
        if (mounted) setSectionCountByForm(counts);
      } catch {
        /* optional */
      }
    })();
    return () => {
      mounted = false;
    };
  }, [rows.length]);

  function switchTab(tab) {
    setViewForm(null);
    setUpdateFormRow(null);
    setActiveTab(tab);
    if (tab === TABS.LIST) {
      loadForms();
    }
  }

  const openView = useCallback(async (row) => {
    const formId = Number(row?.form_id);
    if (!Number.isFinite(formId) || formId <= 0) {
      setError("Cannot open form: invalid form id.");
      return;
    }
    setError("");
    setViewForm(normalizeFormRow(row) || row);
    setViewLoading(true);
    try {
      const fresh = await getForm(formId);
      setViewForm(normalizeFormRow(fresh) || row);
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setViewLoading(false);
    }
  }, []);

  const openUpdate = (row) => {
    const normalized = normalizeFormRow(row) || row;
    setUpdateFormRow(normalized);
    setEditDraft(draftFromRow(normalized));
  };

  const handleCreate = async (e) => {
    e.preventDefault();
    if (!createDraft.title.trim()) {
      setError("Title is required.");
      return;
    }
    setSaving(true);
    try {
      setError("");
      await createForm(buildFormPayload(createDraft));
      setCreateDraft(blankForm);
      await loadForms();
      setActiveTab(TABS.LIST);
      setSuccessPopup("Form has been created successfully.");
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleUpdate = async () => {
    if (!updateFormRow) return;
    if (!editDraft.title?.trim()) {
      setError("Title is required.");
      return;
    }
    const formId = Number(updateFormRow.form_id);
    if (!Number.isFinite(formId) || formId <= 0) {
      setError("Cannot update form: invalid form id.");
      return;
    }
    setSaving(true);
    try {
      setError("");
      await updateForm(formId, buildFormPayload(editDraft));
      await loadForms();
      setUpdateFormRow(null);
      setSuccessPopup("Form update has been completed.");
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setSaving(false);
    }
  };

  const columns = useMemo(() => [
    { key: "form_id", label: "ID" },
    { key: "title", label: "Title" },
    {
      key: "form_type_id",
      label: "Form type",
      render: (r) => (
        <span className="ptw-mgmt-tag">{formTypeName[String(r.form_type_id)] || "—"}</span>
      )
    },
    {
      key: "job_type_id",
      label: "Job type",
      render: (r) => (
        <span className="ptw-mgmt-tag ptw-mgmt-tag--muted">{jobTypeName[String(r.job_type_id)] || "—"}</span>
      )
    },
    {
      key: "section_count",
      label: "Sections",
      render: (r) => (
        <span className="ptw-mgmt-tag">{sectionCountByForm[r.form_id] ?? 0}</span>
      )
    },
    {
      key: "created_date",
      label: "Created",
      render: (r) => formatFormDate(r.created_date)
    },
    {
      key: "actions",
      label: "Actions",
      render: (r) => (
        <div className="ptw-mgmt-table-actions" onClick={(e) => e.stopPropagation()}>
          <button type="button" className="ptw-mgmt-btn ptw-mgmt-btn--view" onClick={() => openView(r)}>
            View
          </button>
          <button type="button" className="ptw-mgmt-btn ptw-mgmt-btn--edit" onClick={() => openUpdate(r)}>
            Update
          </button>
        </div>
      )
    }
  ], [formTypeName, jobTypeName, openView, sectionCountByForm]);

  return (
    <div className="portal-page ptw-mgmt-page ptw-form-management-page">
      <PageHeader
        title="Form Management"
        subtitle="Create PTW forms, map sections via ptw_form_section_map, and manage definitions."
      />
      <ErrorBanner message={error} />

      <div className="ptw-mgmt-shell">
        <div className="ptw-mgmt-tabs" role="tablist">
          <button
            type="button"
            role="tab"
            aria-selected={activeTab === TABS.CREATE}
            className={`ptw-mgmt-tab${activeTab === TABS.CREATE ? " is-active" : ""}`}
            onClick={() => switchTab(TABS.CREATE)}
          >
            Create Form
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={activeTab === TABS.LIST}
            className={`ptw-mgmt-tab${activeTab === TABS.LIST ? " is-active" : ""}`}
            onClick={() => switchTab(TABS.LIST)}
          >
            View All Forms
            {rows.length > 0 ? <span className="ptw-mgmt-tab__count">{rows.length}</span> : null}
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={activeTab === TABS.MAP_SECTIONS}
            className={`ptw-mgmt-tab${activeTab === TABS.MAP_SECTIONS ? " is-active" : ""}`}
            onClick={() => switchTab(TABS.MAP_SECTIONS)}
          >
            Map Sections
          </button>
        </div>

        <div className="ptw-mgmt-body">
          {activeTab === TABS.MAP_SECTIONS ? <FormSectionMapPanel /> : null}

          {activeTab === TABS.CREATE ? (
            <form className="ptw-mgmt-card" onSubmit={handleCreate}>
              <div className="ptw-mgmt-card__header">
                <div>
                  <h2 className="ptw-mgmt-card__title">Create a new form</h2>
                  <p className="ptw-mgmt-card__desc">Define the form metadata. You will be taken to the list after saving.</p>
                </div>
              </div>

              <div className="ptw-mgmt-section">
                <h3 className="ptw-mgmt-section__title">Form details</h3>
                <FormFields
                  draft={createDraft}
                  setDraft={setCreateDraft}
                  formTypeOptions={formTypeOptions}
                  jobTypeOptions={jobTypeOptions}
                />
              </div>

              <div className="ptw-mgmt-card__footer">
                <button type="submit" className="swi-btn swi-btn--primary" disabled={saving}>
                  {saving ? "Creating…" : "Create form"}
                </button>
                <button
                  type="button"
                  className="swi-btn swi-btn--ghost"
                  onClick={() => setCreateDraft(blankForm)}
                  disabled={saving}
                >
                  Clear form
                </button>
              </div>

              <div className="ptw-mgmt-advanced">
                <NestedFormPublishPanel />
              </div>
            </form>
          ) : null}

          {activeTab === TABS.LIST ? (
            <div className="ptw-mgmt-card ptw-mgmt-card--list">
              <div className="ptw-mgmt-card__header ptw-mgmt-card__header--row">
                <div>
                  <h2 className="ptw-mgmt-card__title">All forms</h2>
                  <p className="ptw-mgmt-card__desc">View or update forms. Use Map Sections to link sections to a form.</p>
                </div>
                <button
                  type="button"
                  className="swi-btn swi-btn--ghost"
                  onClick={loadForms}
                  disabled={listLoading}
                >
                  {listLoading ? "Refreshing…" : "Refresh"}
                </button>
              </div>
              <div className="ptw-mgmt-list-meta">
                <span>
                  {listLoading
                    ? "Loading forms…"
                    : `${rows.length} form${rows.length === 1 ? "" : "s"} found`}
                </span>
              </div>
              {listLoading && rows.length === 0 ? (
                <p className="ptw-muted ptw-mgmt-list-loading">Fetching form list…</p>
              ) : null}
              <DataTable
                columns={columns}
                rows={rows}
                keyField="form_id"
                emptyMessage="No forms yet. Switch to Create Form to add your first form."
              />
            </div>
          ) : null}
        </div>
      </div>

      <EntityModal
        open={Boolean(viewForm)}
        title={viewForm ? viewForm.title : "View form"}
        onClose={() => setViewForm(null)}
      >
        {viewForm ? (
          viewLoading ? (
            <p className="ptw-muted">Loading form details…</p>
          ) : (
            <FormDetailView
              form={viewForm}
              formTypeName={formTypeName}
              jobTypeName={jobTypeName}
              sectionCount={sectionCountByForm[viewForm.form_id]}
            />
          )
        ) : null}
      </EntityModal>

      <EntityModal open={Boolean(updateFormRow)} title="Update form" onClose={() => setUpdateFormRow(null)}>
        {updateFormRow ? (
          <>
            <p className="ptw-muted" style={{ marginTop: 0 }}>Form #{updateFormRow.form_id}</p>
            <FormFields
              draft={editDraft}
              setDraft={setEditDraft}
              formTypeOptions={formTypeOptions}
              jobTypeOptions={jobTypeOptions}
            />
            <div className="ptw-row-actions" style={{ marginTop: "1.25rem" }}>
              <button type="button" className="swi-btn swi-btn--primary" onClick={handleUpdate} disabled={saving}>
                {saving ? "Saving…" : "Save changes"}
              </button>
              <button type="button" className="swi-btn swi-btn--ghost" onClick={() => setUpdateFormRow(null)}>
                Cancel
              </button>
            </div>
          </>
        ) : null}
      </EntityModal>

      <EntityModal
        open={Boolean(successPopup)}
        title="Success"
        onClose={() => setSuccessPopup(null)}
      >
        <p className="ptw-mgmt-success-msg">{successPopup}</p>
        <button type="button" className="swi-btn swi-btn--primary" onClick={() => setSuccessPopup(null)}>
          OK
        </button>
      </EntityModal>
    </div>
  );
}
