import type { LabelLayoutConfig } from './labelLayout';

export interface BatchPrintOptions {
  labelLayout?: Partial<LabelLayoutConfig>;
  mergeDataSet?: string;
  pageBottomSpacing?: number;
  pageTopSpacing?: number;
}

export const DEFAULT_MERGED_PRINT_PAGE_BOTTOM_SPACING = 15;
export const DEFAULT_MERGED_PRINT_PAGE_TOP_SPACING = 15;
const POINTS_PER_MM = 72 / 25.4;
const PAPER_FOOTER_KEYS = ['paperFooter', 'firstPaperFooter', 'evenPaperFooter', 'oddPaperFooter', 'lastPaperFooter'] as const;

function normalizeSpacing(value: unknown, fallback: number) {
  if (value === null || value === undefined || value === '') return fallback;
  const spacing = Number(value);
  return Number.isFinite(spacing) && spacing >= 0 ? spacing : fallback;
}

export function applyMergedBatchPrintLayout(printTemplate: any, options: BatchPrintOptions) {
  if (typeof options.mergeDataSet !== 'string' || !options.mergeDataSet.trim() || !Array.isArray(printTemplate?.panels)) return printTemplate;

  const pageBottomSpacing = normalizeSpacing(options.pageBottomSpacing, DEFAULT_MERGED_PRINT_PAGE_BOTTOM_SPACING);
  const pageTopSpacing = normalizeSpacing(options.pageTopSpacing, DEFAULT_MERGED_PRINT_PAGE_TOP_SPACING);
  for (const panel of printTemplate.panels) {
    const currentPaperHeader = Number(panel?.paperHeader);
    panel.paperHeader = Math.max(Number.isFinite(currentPaperHeader) ? currentPaperHeader : 0, pageTopSpacing);

    const paperHeight = Number(panel?.height) * POINTS_PER_MM;
    if (!Number.isFinite(paperHeight) || paperHeight <= 0) continue;
    const maximumPaperFooter = paperHeight - pageBottomSpacing;
    for (const footerKey of PAPER_FOOTER_KEYS) {
      const currentPaperFooter = Number(panel?.[footerKey]);
      if (footerKey !== 'paperFooter' && (!Number.isFinite(currentPaperFooter) || currentPaperFooter <= 0)) continue;
      panel[footerKey] = Math.min(Number.isFinite(currentPaperFooter) && currentPaperFooter > 0 ? currentPaperFooter : paperHeight, maximumPaperFooter);
    }
  }
  return printTemplate;
}

export function getMergedBatchPrintTableStyle(scope = '') {
  const selectorPrefix = scope ? `${scope} ` : '';
  return `
${selectorPrefix}.hiprint-printElement-tableTarget {
  width: 100% !important;
  table-layout: fixed !important;
}
${selectorPrefix}.hiprint-printElement-tableTarget thead tr {
  height: auto !important;
}
${selectorPrefix}.hiprint-printElement-tableTarget thead td,
${selectorPrefix}.hiprint-printElement-tableTarget thead th {
  height: auto !important;
  min-height: 18pt;
  padding-top: 3pt !important;
  padding-bottom: 3pt !important;
  white-space: normal !important;
  overflow: visible !important;
  text-overflow: clip !important;
  overflow-wrap: anywhere !important;
  word-break: break-all !important;
  line-height: 1.4 !important;
  vertical-align: middle !important;
}
${selectorPrefix}.hiprint-printElement-tableTarget tbody tr {
  height: auto !important;
}
${selectorPrefix}.hiprint-printElement-tableTarget tbody td {
  height: auto !important;
  min-height: 18pt;
  padding-top: 3pt !important;
  padding-bottom: 3pt !important;
  white-space: normal !important;
  overflow: visible !important;
  text-overflow: clip !important;
  overflow-wrap: anywhere !important;
  word-break: break-all !important;
  line-height: 1.4 !important;
}`;
}

export function mergePrintDataSet(printDataList: any[], dataSetName: string) {
  const normalizedDataSetName = typeof dataSetName === 'string' ? dataSetName.trim() : '';
  if (!normalizedDataSetName) return printDataList;

  const validPrintDataList = printDataList.filter((item) => item && typeof item === 'object');
  if (!validPrintDataList.length) return [];

  const mergedPrintData = { ...validPrintDataList[0] };
  mergedPrintData[normalizedDataSetName] = validPrintDataList.flatMap((item) => {
    const dataSet = item[normalizedDataSetName];
    return Array.isArray(dataSet) ? dataSet : [];
  });

  return [mergedPrintData];
}
