import React, { useMemo } from "react";
import { normalizeBlockIcons } from "../../utils/blockIcons.js";
import {
  resolvePageContentHeightPx,
  resolvePreviewRowHeightsPx,
} from "../../utils/pageContentRows.js";
import { previewPictureCellHeightPx } from "../../utils/pictureRowLayout.js";
import { normalizeTextBlocks } from "../../utils/textBlocks.js";
import { normalizeCanvasItems } from "../../utils/pictureCanvas.js";
import {
  computePictureRowSpans,
  itemsForPictureCell,
  pictureMergeNextFlags,
} from "../../utils/pictureRowLayout.js";
import PictureCanvasColumn from "./PictureCanvasColumn.jsx";

function displayVal(value) {
  const s = value == null ? "" : String(value).trim();
  return s || "—";
}

function logoSrc(icons, iconId) {
  if (!iconId) return null;
  const row = icons.find((ic) => String(ic.icon_id) === String(iconId));
  return row?.icon_data_url ?? null;
}

function rowLines(text) {
  return String(text || "")
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean);
}

function markerFlags(source = {}) {
  return {
    tips: Boolean(source?.tips ?? source?.marker_tips),
    quality: Boolean(source?.quality ?? source?.marker_quality),
    safety: Boolean(source?.safety ?? source?.marker_safety),
    visual: Boolean(source?.visual ?? source?.marker_visual),
  };
}

const MARKER_ITEMS = [
  { key: "tips", label: "TIPS", symbol: "+" },
  { key: "quality", label: "QUALITY", symbol: "●" },
  { key: "safety", label: "SAFETY", symbol: "◆" },
  { key: "visual", label: "VISUAL", symbol: "◉" },
];

function OperationHeaderCell({ markers }) {
  const active = MARKER_ITEMS.filter((item) => Boolean(markers?.[item.key]));
  return (
    <th className="swi-shot-op-header">
      <span className="swi-shot-op-header-title">OPERATION</span>
      <div className="swi-shot-op-header-legend" aria-label="Operation marker legend">
        {active.map((item) => (
          <span key={item.key} className="swi-shot-op-header-marker">
            <span className={`swi-shot-op-marker-symbol swi-shot-op-marker-symbol--${item.key}`}>
              {item.symbol}
            </span>
            <span className="swi-shot-op-marker-label">{item.label}</span>
          </span>
        ))}
      </div>
    </th>
  );
}

function OperationCell({ text, rowIndex }) {
  const lines = rowLines(text);

  if (!lines.length) {
    return <div className="swi-shot-op-empty">—</div>;
  }

  return (
    <div className="swi-shot-op-cell-layout">
      <ol className="swi-shot-op-list">
        {lines.map((line, lineIdx) => (
          <li key={`${rowIndex}-${lineIdx}`} className="swi-shot-op-item">
            <span className="swi-shot-op-text">{line}</span>
          </li>
        ))}
      </ol>
    </div>
  );
}

function LogoStackCell({ iconIds, icons, showPlus }) {
  const filled = iconIds.filter(Boolean);
  if (!filled.length) {
    return (
      <div className="swi-shot-icon-cell">
        {showPlus ? (
          <span className="doc-logo-plus" aria-label="Plus marker" />
        ) : (
          <span className="swi-shot-op-empty">—</span>
        )}
      </div>
    );
  }

  return (
    <div className="swi-shot-icon-cell doc-logo-stack">
      {filled.map((iconId, idx) => {
        const src = logoSrc(icons, iconId);
        return src ? (
          <img
            key={`${iconId}-${idx}`}
            src={src}
            alt=""
            className="doc-logo-img swi-shot-icon-img"
          />
        ) : null;
      })}
    </div>
  );
}

/**
 * Read-only rendered SWI page using screenshot-style table layout.
 * @param {{ form: object, icons: object[], className?: string }} props
 */
export default function DocumentSubmissionView({ form, icons = [], className = "" }) {
  const textBlocks = normalizeTextBlocks(form);
  const renderBlocks = textBlocks.length
    ? textBlocks
    : [{ block_index: 1, text: "", height_px: 0 }];
  const rowCount = renderBlocks.length;
  const blockIcons = normalizeBlockIcons(form, form, rowCount);
  const canvasItems = normalizeCanvasItems(form);
  const pageMarkers = markerFlags(form?.page_markers || form);
  const rowHeightsPx = useMemo(
    () => resolvePreviewRowHeightsPx(renderBlocks),
    [renderBlocks]
  );
  const pageContentHeightPx = useMemo(
    () => resolvePageContentHeightPx(renderBlocks),
    [renderBlocks]
  );
  const mergeNextFlags = useMemo(
    () => pictureMergeNextFlags(form, rowCount),
    [form, rowCount]
  );
  const pictureRowLayout = useMemo(
    () => computePictureRowSpans(rowCount, mergeNextFlags),
    [rowCount, mergeNextFlags]
  );

  return (
    <div
      className={`doc-submission-view ${className}`.trim()}
      style={{ "--doc-page-content-height": `${pageContentHeightPx}px` }}
    >
      <div className="doc-outer">
        <div className="document-wrap document-wrap--view doc-a4-sheet swi-shot-sheet">
          <div className="swi-shot-meta-row swi-shot-meta-row--top">
            <div className="swi-shot-meta-cell swi-shot-meta-label">JOB INSTRUCTION:</div>
            <div className="swi-shot-meta-cell swi-shot-meta-value">
              {displayVal(form.description)}
            </div>
            <div className="swi-shot-meta-cell swi-shot-meta-label">DOCUMENT N°</div>
            <div className="swi-shot-meta-cell">{displayVal(form.document_no)}</div>
            <div className="swi-shot-meta-cell swi-shot-meta-label">ISSUE DATE</div>
            <div className="swi-shot-meta-cell">{displayVal(form.issue_date)}</div>
            <div className="swi-shot-meta-cell swi-shot-meta-label">CONTROL PLAN</div>
            <div className="swi-shot-meta-cell">—</div>
            <div className="swi-shot-meta-cell swi-shot-meta-label">DATE</div>
            <div className="swi-shot-meta-cell">{displayVal(form.margin_date)}</div>
            <div className="swi-shot-meta-cell swi-shot-meta-label">PAGE</div>
            <div className="swi-shot-meta-cell">{displayVal(form.page)}</div>
          </div>

          <div className="swi-shot-meta-row swi-shot-meta-row--second">
            <div className="swi-shot-meta-cell swi-shot-meta-label">PART NUMBER N°</div>
            <div className="swi-shot-meta-cell">{displayVal(form.part_number)}</div>
            <div className="swi-shot-meta-cell swi-shot-meta-label">DESCRIPTION</div>
            <div className="swi-shot-meta-cell">{displayVal(form.description)}</div>
            <div className="swi-shot-meta-cell swi-shot-meta-label">PROCESS</div>
            <div className="swi-shot-meta-cell">{displayVal(form.process)}</div>
          </div>

          <table className="swi-shot-body-table">
            <colgroup>
              <col className="swi-shot-col-category" />
              <col className="swi-shot-col-safety" />
              <col className="swi-shot-col-no" />
              <col className="swi-shot-col-op" />
              <col className="swi-shot-col-pics" />
            </colgroup>
            <thead>
              <tr className="swi-shot-legend-row">
                <th />
                <th>SAFETY</th>
                <th>N°</th>
                <OperationHeaderCell markers={pageMarkers} />
                <th>VISUAL / SKETCHES / PICTURES</th>
              </tr>
            </thead>
            <tbody>
              {renderBlocks.map((block, rowIndex) => {
                const ids = (blockIcons[String(block.block_index)] || []).filter(Boolean);
                const rowHeightPx = rowHeightsPx[rowIndex];
                return (
                  <tr
                    key={block.block_index}
                    style={rowHeightPx ? { height: `${rowHeightPx}px` } : undefined}
                  >
                    {rowIndex === 0 ? (
                      <td className="swi-shot-category-cell" rowSpan={rowCount}>
                        {/*{displayVal(form.materials_label || "")}*/}
                        {String(form.materials_label ?? "").trim()}
                      </td>
                    ) : null}
                    <td
                      className="swi-shot-icon-col"
                      style={rowHeightPx ? { height: `${rowHeightPx}px` } : undefined}
                    >
                      <LogoStackCell
                        iconIds={ids}
                        icons={icons}
                        showPlus={rowIndex === 0 && Boolean(form.show_logo_plus) && !ids.length}
                      />
                    </td>
                    <td
                      className="swi-shot-no-cell"
                      style={rowHeightPx ? { height: `${rowHeightPx}px` } : undefined}
                    >
                      {rowIndex + 1}
                    </td>
                    <td
                      className="swi-shot-op-col"
                      style={rowHeightPx ? { height: `${rowHeightPx}px` } : undefined}
                    >
                      <OperationCell text={block.text} rowIndex={rowIndex} />
                    </td>
                    {!pictureRowLayout.skip[rowIndex] ? (
                      <td
                        className="swi-shot-pics-col"
                        rowSpan={pictureRowLayout.spans[rowIndex]}
                        style={{
                          height: `${previewPictureCellHeightPx(
                            rowHeightsPx,
                            rowIndex,
                            pictureRowLayout.spans[rowIndex]
                          )}px`,
                        }}
                      >
                        <PictureCanvasColumn
                          items={itemsForPictureCell(
                            canvasItems,
                            rowIndex,
                            pictureRowLayout.spans[rowIndex],
                            rowHeightsPx
                          )}
                          readOnly
                          rowMode
                          stageHeightPx={previewPictureCellHeightPx(
                            rowHeightsPx,
                            rowIndex,
                            pictureRowLayout.spans[rowIndex]
                          )}
                        />
                      </td>
                    ) : null}
                  </tr>
                );
              })}
            </tbody>
          </table>

          {/*
          <div className="doc-footer doc-view-footer swi-shot-footer">
            <span>
              {form.footer_url ? (
                <a href={form.footer_url} target="_blank" rel="noreferrer">
                  {form.footer_url}
                </a>
              ) : (
                "—"
              )}
            </span>
            <span>{displayVal(form.footer_page)}</span>
          </div>
          */}
        </div>
      </div>
    </div>
  );
}
