import React, { useEffect, useMemo, useState } from "react";
import DocumentCreatedSuccessModal from "../../components/admin/DocumentCreatedSuccessModal.jsx";
import GlassSelect from "../../components/common/GlassSelect.jsx";
import {
  buildCreateDocumentPayload,
  createDocument,
  fetchDocuments,
  fetchLookupTables,
  nextDocumentIds,
} from "../../services/swiApi.js";
import { getApiErrorMessage } from "../../utils/apiError.js";

const emptyForm = () => ({
  document_id: "",
  document_number: "",
  document_name: "",
  document_status_id: "",
  location_id: "",
  department_id: "",
  job_area_id: "",
  process_name: "",
  page_count: "1",
  previous_document_id: "",
});

function lookupLabel(items, idKey, nameKey, value) {
  if (!value) return "—";
  const match = (items || []).find(
    (item) => String(item[idKey]) === String(value)
  );
  return match?.[nameKey] || "—";
}

export default function CreateDocumentPage({ onNavigate }) {
  const [form, setForm] = useState(emptyForm);
  const [documents, setDocuments] = useState([]);
  const [lookups, setLookups] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [createdDocument, setCreatedDocument] = useState(null);

  const resetToNextIds = (docs) => {
    const ids = nextDocumentIds(docs);
    setForm({
      ...emptyForm(),
      document_id: String(ids.document_id),
      document_number: String(ids.document_number),
    });
  };

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [tables, docs] = await Promise.all([
          fetchLookupTables(),
          fetchDocuments(),
        ]);
        if (cancelled) return;
        setLookups(tables);
        setDocuments(docs);
        const ids = nextDocumentIds(docs);
        setForm((f) => ({
          ...f,
          document_id: String(ids.document_id),
          document_number: String(ids.document_number),
        }));
      } catch (e) {
        if (!cancelled) {
          setError(getApiErrorMessage(e, "Could not load form data."));
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const set = (key, value) => {
    setForm((f) => {
      const next = { ...f, [key]: value };
      if (key === "document_id" && value !== "") {
        const ids = nextDocumentIds(documents, value);
        next.document_number = String(ids.document_number);
      }
      return next;
    });
  };

  const locationOptions = useMemo(
    () =>
      (lookups?.locations || []).map((l) => ({
        value: l.location_id,
        label: l.location_name,
      })),
    [lookups]
  );

  const departmentOptions = useMemo(
    () =>
      (lookups?.departments || []).map((d) => ({
        value: d.department_id,
        label: d.department_name,
      })),
    [lookups]
  );

  const jobAreaOptions = useMemo(
    () =>
      (lookups?.jobAreas || []).map((j) => ({
        value: j.job_area_id,
        label: j.job_area_name,
      })),
    [lookups]
  );

  const submit = async (e) => {
    e.preventDefault();
    setError("");
    setSaving(true);
    try {
      const payload = buildCreateDocumentPayload(form);
      const saved = await createDocument(payload);
      const docs = await fetchDocuments();
      setDocuments(docs);
      resetToNextIds(docs);
      setCreatedDocument(saved);
    } catch (e) {
      setError(getApiErrorMessage(e, "Create failed."));
    } finally {
      setSaving(false);
    }
  };

  const handleViewDocuments = () => {
    if (!createdDocument) return;
    onNavigate?.("my-documents", {
      documentId: createdDocument.document_id,
      documentNumber: createdDocument.document_number,
    });
    setCreatedDocument(null);
  };

  const handleReset = () => {
    setError("");
    setCreatedDocument(null);
    resetToNextIds(documents);
  };

  const previewName = form.document_name.trim() || "Untitled document";
  const previewPlant = lookupLabel(
    lookups?.locations,
    "location_id",
    "location_name",
    form.location_id
  );
  const previewDepartment = lookupLabel(
    lookups?.departments,
    "department_id",
    "department_name",
    form.department_id
  );
  const previewJobArea = lookupLabel(
    lookups?.jobAreas,
    "job_area_id",
    "job_area_name",
    form.job_area_id
  );

  if (loading) {
    return (
      <div className="swi-admin-create-page">
        <div className="swi-panel swi-admin-create-loading">
          <p className="swi-muted">Loading create document form…</p>
        </div>
      </div>
    );
  }

  return (
    <div className="swi-admin-create-page">
      <header className="portal-page-header portal-page-header--solo">
        <div className="portal-page-header__text">
          <h1 className="portal-page-title">Create document</h1>
          <p className="portal-page-subtitle">
            Register a new SWI document record. After creation, assign it to a
            user from the Assign document page.
          </p>
        </div>
      </header>

      {error ? (
        <div className="swi-error" role="alert">
          {error}
        </div>
      ) : null}

      <div className="swi-admin-create-layout">
        <form
          className="swi-admin-create-form swi-panel"
          onSubmit={submit}
          noValidate
        >
          <div className="swi-admin-create-form__intro">
            <div>
              <h2 className="swi-admin-create-form__heading">
                New document registration
              </h2>
              <p className="swi-admin-create-form__lead">
                Complete the fields below. Required items are marked with an
                asterisk.
              </p>
            </div>
            <div className="swi-admin-create-form__ids">
              <span className="swi-admin-create-id-chip">
                <span className="swi-admin-create-id-chip__label">Document ID</span>
                <strong>{form.document_id || "—"}</strong>
              </span>
              <span className="swi-admin-create-id-chip">
                <span className="swi-admin-create-id-chip__label">Status</span>
                <span className="swi-status-badge swi-status-badge--opened">
                  Opened
                </span>
              </span>
            </div>
          </div>

          <section className="swi-form-section" aria-labelledby="create-section-details">
            <div className="swi-form-section__head">
              <h3 id="create-section-details" className="swi-form-section__title">
                Document details
              </h3>
              <p className="swi-form-section__desc">
                Core identification used across the SWI library.
              </p>
            </div>
            <div className="swi-form-grid">
              <div className="swi-form-row">
                <label htmlFor="document_number">
                  Revision number <span className="swi-required">*</span>
                </label>
                <input
                  id="document_number"
                  className="swi-input"
                  type="number"
                  min={1}
                  value={form.document_number}
                  onChange={(e) => set("document_number", e.target.value)}
                  required
                />
                <p className="swi-field-hint">
                  Revision sequence for document ID {form.document_id || "—"}.
                </p>
              </div>
              <div className="swi-form-row swi-form-row--full">
                <label htmlFor="document_name">
                  Document name <span className="swi-required">*</span>
                </label>
                <input
                  id="document_name"
                  className="swi-input"
                  value={form.document_name}
                  onChange={(e) => set("document_name", e.target.value)}
                  placeholder="e.g. Standard work instruction — line startup"
                  required
                />
                <p className="swi-field-hint">
                  Use the official title as it should appear to users.
                </p>
              </div>
            </div>
          </section>

          <section className="swi-form-section" aria-labelledby="create-section-location">
            <div className="swi-form-section__head">
              <h3 id="create-section-location" className="swi-form-section__title">
                Location &amp; scope
              </h3>
              <p className="swi-form-section__desc">
                Organizational context for filtering and reporting.
              </p>
            </div>
            <div className="swi-form-grid">
              <div className="swi-form-row">
                <label htmlFor="location_id">Plant</label>
                <GlassSelect
                  id="location_id"
                  value={form.location_id}
                  onChange={(value) => set("location_id", value)}
                  placeholder="Select plant"
                  options={locationOptions}
                  aria-label="Plant"
                />
              </div>
              <div className="swi-form-row">
                <label htmlFor="department_id">Major work area</label>
                <GlassSelect
                  id="department_id"
                  value={form.department_id}
                  onChange={(value) => set("department_id", value)}
                  placeholder="Select major work area"
                  options={departmentOptions}
                  aria-label="Major work area"
                />
              </div>
              <div className="swi-form-row">
                <label htmlFor="job_area_id">Job area</label>
                <GlassSelect
                  id="job_area_id"
                  value={form.job_area_id}
                  onChange={(value) => set("job_area_id", value)}
                  placeholder="Select job area"
                  options={jobAreaOptions}
                  aria-label="Job area"
                />
              </div>
            </div>
          </section>

          <section className="swi-form-section" aria-labelledby="create-section-process">
            <div className="swi-form-section__head">
              <h3 id="create-section-process" className="swi-form-section__title">
                Process information
              </h3>
              <p className="swi-form-section__desc">
                Optional process reference for the instruction.
              </p>
            </div>
            <div className="swi-form-grid">
              <div className="swi-form-row swi-form-row--full">
                <label htmlFor="process_name">Process name</label>
                <input
                  id="process_name"
                  className="swi-input"
                  value={form.process_name}
                  onChange={(e) => set("process_name", e.target.value)}
                  placeholder="e.g. Assembly line changeover"
                />
              </div>
            </div>
          </section>

          <div className="swi-form-actions swi-admin-create-form__actions">
            <button
              type="button"
              className="swi-btn swi-btn--ghost"
              onClick={handleReset}
              disabled={saving}
            >
              Clear form
            </button>
            <button
              type="submit"
              className="swi-btn swi-btn--primary"
              disabled={saving || !form.document_name.trim()}
            >
              {saving ? "Creating…" : "Create document"}
            </button>
          </div>
        </form>

        <aside className="swi-admin-create-aside">
          <div className="swi-panel swi-admin-create-summary">
            <h2 className="swi-admin-create-summary__title">Registration preview</h2>
            <p className="swi-admin-create-summary__lead">
              Review the record before submission.
            </p>

            <dl className="swi-admin-create-summary__list">
              <div>
                <dt>Document name</dt>
                <dd>{previewName}</dd>
              </div>
              <div>
                <dt>Document ID</dt>
                <dd>{form.document_id || "—"}</dd>
              </div>
              <div>
                <dt>Revision</dt>
                <dd>#{form.document_number || "—"}</dd>
              </div>
              <div>
                <dt>Initial status</dt>
                <dd>
                  <span className="swi-status-badge swi-status-badge--opened">
                    Opened
                  </span>
                </dd>
              </div>
              <div>
                <dt>Plant</dt>
                <dd>{previewPlant}</dd>
              </div>
              <div>
                <dt>Major work area</dt>
                <dd>{previewDepartment}</dd>
              </div>
              <div>
                <dt>Job area</dt>
                <dd>{previewJobArea}</dd>
              </div>
              <div>
                <dt>Process</dt>
                <dd>{form.process_name.trim() || "—"}</dd>
              </div>
            </dl>
          </div>

          <div className="swi-panel swi-admin-create-steps">
            <h2 className="swi-admin-create-steps__title">Document workflow</h2>
            <ol className="swi-admin-create-steps__list">
              <li className="is-current">
                <span className="swi-admin-create-steps__num">1</span>
                <div>
                  <strong>Create document</strong>
                  <p>Record is saved with status Opened.</p>
                </div>
              </li>
              <li>
                <span className="swi-admin-create-steps__num">2</span>
                <div>
                  <strong>Assign document</strong>
                  <p>Select a user and set status to Assigned.</p>
                </div>
              </li>
              <li>
                <span className="swi-admin-create-steps__num">3</span>
                <div>
                  <strong>User completion</strong>
                  <p>Assignee fills pages and submits the SWI.</p>
                </div>
              </li>
            </ol>
          </div>
        </aside>
      </div>

      <DocumentCreatedSuccessModal
        open={Boolean(createdDocument)}
        document={createdDocument}
        onViewDocuments={handleViewDocuments}
      />
    </div>
  );
}
