import React, { useEffect, useState } from "react";
import {
  fetchAssignmentDocumentPages,
} from "../../services/swiApi.js";
import DocumentSubmissionView from "../../components/swi/DocumentSubmissionView.jsx";
import { getApiErrorMessage } from "../../utils/apiError.js";
import { normalizeBlockIcons } from "../../utils/blockIcons.js";
import { syncPageRowAssets } from "../../utils/pageContentRows.js";
import { normalizeCanvasItems } from "../../utils/pictureCanvas.js";
import { stampPictureCellRowSpans } from "../../utils/pictureRowLayout.js";
import { normalizeTextBlocks } from "../../utils/textBlocks.js";
import "../../styles/documentBuilder.css";

function formatDate(value) {
  if (!value) return "";
  const d = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(d.getTime())) return "";
  const dd = String(d.getDate()).padStart(2, "0");
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const yyyy = d.getFullYear();
  return `${dd}/${mm}/${yyyy}`;
}

function parseDraft(raw) {
  if (raw == null || raw === "") return {};
  if (typeof raw === "object") return raw;
  try {
    return JSON.parse(raw);
  } catch {
    return {};
  }
}

function pageHasContent(page) { 
  const blocks = page.blocks || [];
  const hasBlockText = blocks.some((b) => String(b.text || "").trim());
  const hasMarkers = Boolean(
    page.marker_tips || page.marker_quality || page.marker_safety || page.marker_visual
  );
  const hasIcons = blocks.some(
    (b) => Array.isArray(b.icon_ids) && b.icon_ids.length > 0
  );
  const hasImages =
    (Array.isArray(page.picture_canvas) &&
      page.picture_canvas.some((img) => img.image_data_url)) ||
    (Array.isArray(page.images) &&
      page.images.some((img) => img.image_data_url));
  return hasBlockText || hasMarkers || hasIcons || hasImages;
}

function pageToForm(page, documentMeta, totalPages) {
  const draft = parseDraft(documentMeta?.form_draft);
  const pageNum = page.page_num || 1;
  const rawBlockIcons = {};
  for (const block of page.blocks || []) {
    const key = String(block.block_index);
    if (!rawBlockIcons[key]) {
      rawBlockIcons[key] = Array(6).fill("");
    }
    const ids = Array.isArray(block.icon_ids)
      ? block.icon_ids
      : block.icon_id
        ? [block.icon_id]
        : [];
    ids.forEach((id, i) => {
      if (i < rawBlockIcons[key].length && id) {
        rawBlockIcons[key][i] = String(id);
      }
    });
  }

  const imageSlots = {};
  for (const img of page.images || []) {
    if (img.image_data_url) {
      imageSlots[String(Number(img.slot_index) - 1)] = img.image_data_url;
    }
  }

  const text_blocks = normalizeTextBlocks({
    blocks: (page.blocks || []).map((block) => ({
      block_index: block.block_index,
      text: block.text,
      height_px: block.height_px,
      pic_merge_next: Boolean(block.pic_merge_next),
    })),
  });
  const picture_merge_next = {};
  for (const block of page.blocks || []) {
    picture_merge_next[String(block.block_index)] = Boolean(block.pic_merge_next);
  }
  const page_markers = {
    tips: Boolean(page.page_markers?.tips ?? page.marker_tips),
    quality: Boolean(page.page_markers?.quality ?? page.marker_quality),
    safety: Boolean(page.page_markers?.safety ?? page.marker_safety),
    visual: Boolean(page.page_markers?.visual ?? page.marker_visual),
  };

  const loaded = syncPageRowAssets({
    margin_date: draft.margin_date || formatDate(documentMeta?.issued_at),
    margin_ref: draft.margin_ref || (documentMeta?.document_id
      ? `Doc-${documentMeta.document_id}`
      : ""),
    station: documentMeta?.location_name || "",
    job_area: documentMeta?.job_area_name || "",
    document_no:
      documentMeta?.document_number != null
        ? String(documentMeta.document_number)
        : "",
    issue_date: draft.issue_date || formatDate(documentMeta?.issued_at),
    part_number: draft.part_number || "",
    page: `${pageNum}/${totalPages}`,
    description: documentMeta?.document_name || "",
    process: documentMeta?.process_name || "",
    materials_label: page.page_header || "",
    marker_tips: page_markers.tips,
    marker_quality: page_markers.quality,
    marker_safety: page_markers.safety,
    marker_visual: page_markers.visual,
    page_markers,
    text_blocks,
    block_icons: normalizeBlockIcons(
      { block_icons: rawBlockIcons },
      {},
      text_blocks.length
    ),
    block_logo_counts: page.block_logo_counts || {},
    show_logo_plus: draft.show_logo_plus !== false,
    footer_url: draft.footer_url || "https://www.v-swi.com/Details.aspx",
    footer_page: `${pageNum}/${totalPages}`,
    image_slots: imageSlots,
    picture_merge_next,
    picture_canvas: normalizeCanvasItems({
      picture_canvas: page.picture_canvas,
      image_slots: imageSlots,
    }),
  });
  return {
    ...loaded,
    picture_canvas: stampPictureCellRowSpans(loaded),
  };
}

export default function SubmittedDocumentPage({
  documentId,
  documentNumber,
  onBack,
}) {
  const [payload, setPayload] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const data = await fetchAssignmentDocumentPages(
          documentId,
          documentNumber
        );
        if (!cancelled) setPayload(data);
      } catch (e) {
        if (!cancelled) {
          setError(getApiErrorMessage(e, "Could not load submitted document."));
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [documentId, documentNumber]);

  if (loading) {
    return <p className="swi-muted">Loading document…</p>;
  }

  if (error) {
    return (
      <>
        <button
          type="button"
          className="swi-btn swi-btn--ghost doc-back-btn"
          onClick={onBack}
        >
          ← Back to assignments
        </button>
        <div className="swi-error" role="alert">
          {error}
        </div>
      </>
    );
  }

  const doc = {
    document_id: payload?.document_id,
    document_number: payload?.document_number,
    document_name: payload?.document_name,
    issued_at: payload?.issued_at,
    location_name: payload?.location_name,
    job_area_name: payload?.job_area_name,
    process_name: payload?.process_name,
    form_draft: payload?.form_draft,
  };
  const pages = Array.isArray(payload?.pages) ? payload.pages : [];
  const totalPages = pages.length || 1;
  const pagesWithContent = pages.filter(pageHasContent);

  return (
    <div className="doc-builder doc-builder--full-width">
      <header className="portal-page-header portal-page-header--solo">
        <div className="portal-page-header__text">
          <button
            type="button"
            className="swi-btn swi-btn--ghost doc-back-btn"
            onClick={onBack}
          >
            ← Back to assignments
          </button>
          <h1 className="portal-page-title">Submitted document</h1>
          <p className="portal-page-subtitle">
            {doc.document_name || "Document"} · ID {documentId} · #
            {documentNumber}
            {pages.length ? ` · ${pages.length} page(s)` : ""}
          </p>
        </div>
      </header>

      {!pagesWithContent.length ? (
        <div className="swi-panel">
          <p className="swi-muted">
            No answers saved yet. Use <strong>Fill form</strong> to complete
            this document first.
          </p>
        </div>
      ) : (
        pagesWithContent.map((page) => (
          <div key={page.page_id || page.page_num} className="doc-submission-page-block">
            <h2 className="doc-submission-page-title">
              Page {page.page_num}
              {page.page_id ? ` · ID ${page.page_id}` : ""}
            </h2>
            <DocumentSubmissionView
              form={pageToForm(page, doc, totalPages)}
              icons={payload?.icons || []}
            />
          </div>
        ))
      )}

      <div className="swi-form-actions">
        <button type="button" className="swi-btn" onClick={() => window.print()}>
          Print / Save as PDF
        </button>
      </div>
    </div>
  );
}
