import type { PdfTextLayoutEdit } from './pdfLayoutEditor';

export type OfficialFormPreviewFieldKey = 'initiativeTitle' | 'authorGroup' | 'workUnit' | 'contactInfo';

export type OfficialFormPreviewFields = Record<OfficialFormPreviewFieldKey, string>;

type OfficialFormPreviewFieldDef = {
  key: OfficialFormPreviewFieldKey;
  label: string;
  placeholder: string;
  maxLength: number;
  multiline?: boolean;
  page: number;
  x: number;
  y: number;
  fontSize: number;
  lineHeight: number;
  fontName: PdfTextLayoutEdit['fontName'];
  colorHex: string;
};

export const OFFICIAL_FORM_PREVIEW_FIELD_DEFS: OfficialFormPreviewFieldDef[] = [
  {
    key: 'initiativeTitle',
    label: 'Tên sáng kiến',
    placeholder: 'Nhập tên sáng kiến để phủ lên bản xem trước',
    maxLength: 240,
    multiline: true,
    page: 1,
    x: 84,
    y: 530,
    fontSize: 13,
    lineHeight: 16,
    fontName: 'TimesRomanBold',
    colorHex: '#111827',
  },
  {
    key: 'authorGroup',
    label: 'Tác giả/nhóm tác giả',
    placeholder: 'Nhập tên tác giả hoặc nhóm tác giả',
    maxLength: 240,
    multiline: true,
    page: 1,
    x: 84,
    y: 492,
    fontSize: 12,
    lineHeight: 15,
    fontName: 'TimesRoman',
    colorHex: '#111827',
  },
  {
    key: 'workUnit',
    label: 'Đơn vị công tác',
    placeholder: 'Nhập đơn vị công tác',
    maxLength: 200,
    page: 1,
    x: 84,
    y: 456,
    fontSize: 12,
    lineHeight: 15,
    fontName: 'TimesRoman',
    colorHex: '#111827',
  },
  {
    key: 'contactInfo',
    label: 'Thông tin liên hệ',
    placeholder: 'Số điện thoại, email',
    maxLength: 220,
    multiline: true,
    page: 1,
    x: 84,
    y: 420,
    fontSize: 11,
    lineHeight: 14,
    fontName: 'TimesRoman',
    colorHex: '#111827',
  },
];

export const EMPTY_OFFICIAL_FORM_PREVIEW_FIELDS: OfficialFormPreviewFields = {
  initiativeTitle: '',
  authorGroup: '',
  workUnit: '',
  contactInfo: '',
};

function toText(value: unknown): string {
  if (value == null) return '';
  return String(value).trim();
}

function sanitizeValue(value: string, maxLength: number): string {
  const compact = value.replace(/\s+\n/g, '\n').replace(/\n\s+/g, '\n').trim();
  if (compact.length <= maxLength) return compact;
  return compact.slice(0, maxLength);
}

function readTrangBiaValue(official: Record<string, unknown>, key: string): string {
  const trangBia = official['TRANG BÌA'];
  if (!trangBia || typeof trangBia !== 'object') return '';
  return toText((trangBia as Record<string, unknown>)[key]);
}

export function buildInitialOfficialFormPreviewFields(
  officialBieuMau: Record<string, unknown>,
): OfficialFormPreviewFields {
  const next: OfficialFormPreviewFields = {
    initiativeTitle: readTrangBiaValue(officialBieuMau, 'Tên sáng kiến (Tiếng Việt)'),
    authorGroup: readTrangBiaValue(officialBieuMau, 'Tác giả/nhóm tác giả sáng kiến'),
    workUnit: readTrangBiaValue(officialBieuMau, 'Đơn vị công tác'),
    contactInfo: readTrangBiaValue(officialBieuMau, 'Thông tin liên hệ (Điện thoại, Email)'),
  };
  return sanitizeOfficialFormPreviewFields(next);
}

export function sanitizeOfficialFormPreviewFields(input: Partial<OfficialFormPreviewFields>): OfficialFormPreviewFields {
  const byKey = new Map(OFFICIAL_FORM_PREVIEW_FIELD_DEFS.map((x) => [x.key, x]));
  return {
    initiativeTitle: sanitizeValue(toText(input.initiativeTitle), byKey.get('initiativeTitle')?.maxLength ?? 240),
    authorGroup: sanitizeValue(toText(input.authorGroup), byKey.get('authorGroup')?.maxLength ?? 240),
    workUnit: sanitizeValue(toText(input.workUnit), byKey.get('workUnit')?.maxLength ?? 200),
    contactInfo: sanitizeValue(toText(input.contactInfo), byKey.get('contactInfo')?.maxLength ?? 220),
  };
}

export function hasOfficialFormPreviewFieldChanges(
  fields: OfficialFormPreviewFields,
  baseFields: OfficialFormPreviewFields,
): boolean {
  return (
    fields.initiativeTitle !== baseFields.initiativeTitle ||
    fields.authorGroup !== baseFields.authorGroup ||
    fields.workUnit !== baseFields.workUnit ||
    fields.contactInfo !== baseFields.contactInfo
  );
}

export function toOfficialFormPreviewOverlayEdits(fields: OfficialFormPreviewFields): PdfTextLayoutEdit[] {
  return OFFICIAL_FORM_PREVIEW_FIELD_DEFS.map((def) => {
    const value = fields[def.key];
    return {
      id: `preview-${def.key}`,
      text: value,
      page: def.page,
      x: def.x,
      y: def.y,
      fontSize: def.fontSize,
      lineHeight: def.lineHeight,
      boxWidth: 420,
      letterSpacing: 0,
      textAlign: 'left',
      fontName: def.fontName,
      colorHex: def.colorHex,
    } satisfies PdfTextLayoutEdit;
  }).filter((x) => x.text.trim().length > 0);
}
