import React, { useEffect, useMemo, useState } from "react";
import {
  fetchAssignmentDocumentPages,
  fetchMyAssignments,
} from "../../services/swiApi.js";
import { getApiErrorMessage } from "../../utils/apiError.js";

function pageLabel(page, docLabel) {
  const header = page.page_header?.trim();
  const title =
    header && header !== "MATERIALS"
      ? header
      : page.blocks?.find((b) => b.text?.trim())?.text?.slice(0, 40) ||
        "Page content";
  return `${docLabel} · Page ${page.page_num}${page.page_id ? ` (ID ${page.page_id})` : ""} — ${title}`;
}

/**
 * @param {{
 *   open: boolean,
 *   onClose: () => void,
 *   targetDocumentId: number,
 *   targetDocumentNumber: number,
 *   targetDocumentName?: string,
 *   copying?: boolean,
 *   onConfirm: (sourcePageId: number) => void,
 * }} props
 */
export default function CopyPageModal({
  open,
  onClose,
  targetDocumentId,
  targetDocumentNumber,
  targetDocumentName,
  copying = false,
  onConfirm,
}) {
  const [assignments, setAssignments] = useState([]);
  const [pagesByDoc, setPagesByDoc] = useState({});
  const [loading, setLoading] = useState(false);
  const [loadingPages, setLoadingPages] = useState(false);
  const [error, setError] = useState("");
  const [sourceDocKey, setSourceDocKey] = useState("");
  const [sourcePageId, setSourcePageId] = useState("");

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setError("");
    setSourceDocKey("");
    setSourcePageId("");
    setLoading(true);
    fetchMyAssignments()
      .then((rows) => {
        if (!cancelled) setAssignments(rows || []);
      })
      .catch((e) => {
        if (!cancelled) {
          setError(getApiErrorMessage(e, "Could not load your documents."));
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [open]);

  const docOptions = useMemo(
    () =>
      assignments.map((a) => ({
        key: `${a.document_id}-${a.document_number}`,
        document_id: a.document_id,
        document_number: a.document_number,
        label: a.document_name || `Document ${a.document_id}`,
      })),
    [assignments]
  );

  useEffect(() => {
    if (!open || !sourceDocKey) return;
    const doc = docOptions.find((d) => d.key === sourceDocKey);
    if (!doc) return;
    if (pagesByDoc[sourceDocKey]) return;

    let cancelled = false;
    setLoadingPages(true);
    setError("");
    fetchAssignmentDocumentPages(doc.document_id, doc.document_number)
      .then((res) => {
        if (!cancelled) {
          setPagesByDoc((prev) => ({
            ...prev,
            [sourceDocKey]: res?.pages || [],
          }));
        }
      })
      .catch((e) => {
        if (!cancelled) {
          setError(getApiErrorMessage(e, "Could not load pages."));
        }
      })
      .finally(() => {
        if (!cancelled) setLoadingPages(false);
      });

    return () => {
      cancelled = true;
    };
  }, [open, sourceDocKey, docOptions, pagesByDoc]);

  const sourcePages = sourceDocKey ? pagesByDoc[sourceDocKey] || [] : [];
  const selectedDoc = docOptions.find((d) => d.key === sourceDocKey);

  if (!open) return null;

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!sourcePageId) {
      setError("Select a page to copy.");
      return;
    }
    onConfirm(Number(sourcePageId));
  };

  return (
    <div className="swi-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="swi-modal swi-copy-page-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="copy-page-modal-title"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="swi-modal__head">
          <h2 id="copy-page-modal-title" className="swi-modal__title">
            Copy page into this document
          </h2>
          <button
            type="button"
            className="swi-modal__close"
            aria-label="Close"
            onClick={onClose}
          >
            ×
          </button>
        </header>

        <p className="swi-muted swi-copy-page-modal__intro">
          Copy all content (text blocks, logos, images) from any of your assigned
          documents into{" "}
          <strong>{targetDocumentName || `document ${targetDocumentId}`}</strong>.
          The new page gets its own page ID and is appended in sequence.
        </p>

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

        <form className="swi-copy-page-modal__form" onSubmit={handleSubmit}>
          <div className="swi-form-row swi-form-row--full">
            <label htmlFor="copy-source-doc">Source document</label>
            <select
              id="copy-source-doc"
              className="swi-select"
              value={sourceDocKey}
              disabled={loading || copying}
              onChange={(e) => {
                setSourceDocKey(e.target.value);
                setSourcePageId("");
              }}
            >
              <option value="">— Select document —</option>
              {docOptions.map((d) => (
                <option key={d.key} value={d.key}>
                  {d.label} (ID {d.document_id} · #{d.document_number})
                  {d.document_id === targetDocumentId &&
                  d.document_number === targetDocumentNumber
                    ? " — current"
                    : ""}
                </option>
              ))}
            </select>
          </div>

          <div className="swi-form-row swi-form-row--full">
            <label htmlFor="copy-source-page">Source page</label>
            <select
              id="copy-source-page"
              className="swi-select"
              value={sourcePageId}
              disabled={!sourceDocKey || loadingPages || copying}
              onChange={(e) => setSourcePageId(e.target.value)}
            >
              <option value="">
                {loadingPages
                  ? "Loading pages…"
                  : !sourceDocKey
                    ? "Select a document first"
                    : sourcePages.length
                      ? "— Select page —"
                      : "No saved pages in this document"}
              </option>
              {sourcePages.map((p) => (
                <option key={p.page_id} value={p.page_id}>
                  {pageLabel(p, selectedDoc?.label || "Document")}
                </option>
              ))}
            </select>
          </div>

          <div className="swi-modal-actions">
            <button
              type="button"
              className="swi-btn swi-btn--ghost"
              disabled={copying}
              onClick={onClose}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="swi-btn swi-btn--primary"
              disabled={copying || !sourcePageId}
            >
              {copying ? "Copying…" : "Copy page here"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
