/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React from 'react';
import { HRDocument } from '../../types';

interface RichEditorContentProps {
  editorRef: React.RefObject<HTMLDivElement | null>;
  isHtmlMode: boolean;
  showPreviewMode: boolean;
  content: string;
  setContent: (val: string) => void;
  handleInput: () => void;
  saveSelection: () => void;
  applyCopiedFormat: () => void;
  isLetterheadMode: boolean;
  letterheadHeight: number;
  isIkiLetterhead: boolean;
  showFormattingMarks: boolean;
  paperSize: 'A4' | 'F4';
  effectiveTopMargin: number;
  effectiveBottomMargin: number;
  marginTop: number;
  marginBottom: number;
  marginLeft: number;
  marginRight: number;
  fontFamily: string;
  fontSize: string;
  lineHeight: string;
  isFormatPainterActive: boolean;
  customKopAtas?: string;
  customKopBawah?: string;
  documentData?: HRDocument;
}

export default function RichEditorContent({
  editorRef,
  isHtmlMode,
  showPreviewMode,
  content,
  setContent,
  handleInput,
  saveSelection,
  applyCopiedFormat,
  isLetterheadMode,
  letterheadHeight,
  isIkiLetterhead,
  showFormattingMarks,
  paperSize,
  effectiveTopMargin,
  effectiveBottomMargin,
  marginTop,
  marginBottom,
  marginLeft,
  marginRight,
  fontFamily,
  fontSize,
  lineHeight,
  isFormatPainterActive,
  customKopAtas,
  customKopBawah,
  documentData
}: RichEditorContentProps) {
  if (isHtmlMode) {
    return (
      <textarea
        id="a4-document-paper-html"
        value={content}
        onChange={(e) => {
          const val = e.target.value;
          setContent(val);
        }}
        className="w-full bg-slate-950 text-emerald-400 font-mono text-xs leading-relaxed p-8 outline-none border border-slate-800 rounded-b-xl shadow-inner focus:ring-1 focus:ring-emerald-500/25 overflow-y-auto resize-none"
        style={{
          minHeight: paperSize === 'A4' ? '297mm' : '330mm',
          boxSizing: 'border-box',
        }}
        placeholder="<!-- Tulis atau modifikasi kode HTML surat di sini. Gunakan tag standar. -->"
      />
    );
  }

  return (
    <>
      <style>{`
        #a4-document-paper > .document-editor-content > div {
          padding: 0 !important;
        }
        .hide-digital-kop .digital-kop-surat { display: none !important; }
        @media print {
          @page { 
            size: ${paperSize === 'A4' ? '210mm 297mm' : '215mm 330mm'}; 
            margin-top: ${marginTop}cm !important;
            margin-bottom: ${marginBottom}cm !important;
            margin-left: 0 !important;
            margin-right: 0 !important;
          }
          @page :first {
            margin-top: 0 !important;
            margin-bottom: 0 !important;
            margin-left: 0 !important;
            margin-right: 0 !important;
          }
          #a4-document-paper {
            min-height: ${paperSize === 'A4' ? '297mm' : '330mm'} !important;
            height: auto !important;
            padding: 0 !important;
            border: none !important;
            box-shadow: none !important;
            position: relative !important;
          }
          #a4-document-paper > .document-editor-content {
            padding-top: ${(isIkiLetterhead || isLetterheadMode) ? `${effectiveTopMargin}cm` : `${marginTop}cm`} !important;
            padding-bottom: ${isIkiLetterhead ? `${effectiveBottomMargin}cm` : `${marginBottom}cm`} !important;
            padding-left: ${marginLeft}cm !important;
            padding-right: ${marginRight}cm !important;
          }
          #a4-document-paper > .iki-footer {
            position: absolute !important;
            top: ${paperSize === 'A4' ? '29.7cm' : '33.0cm'} !important;
            bottom: auto !important;
            transform: translateY(-100%) !important;
          }
        }
        #a4-document-paper.show-formatting-marks p {
          position: relative !important; outline: 1px dashed rgba(14, 165, 233, 0.45) !important; outline-offset: 1px;
        }
        #a4-document-paper.show-formatting-marks p::after {
          content: '¶'; position: absolute; right: -15px; top: 0; color: rgba(14, 165, 233, 0.65); font-weight: bold; font-family: monospace;
        }
        #a4-document-paper.show-formatting-marks div { outline: 1px dashed rgba(220, 38, 38, 0.25) !important; }
        #a4-document-paper.show-formatting-marks table { outline: 1px dashed rgba(16, 185, 129, 0.45) !important; }
      `}</style>
      <div
        id="a4-document-paper"
        className={`bg-white text-black border border-slate-200 transition-all text-justify rounded-b-xl flex flex-col overflow-hidden ${
          (isLetterheadMode || isIkiLetterhead) ? 'hide-digital-kop' : ''
        } ${showFormattingMarks ? 'show-formatting-marks' : ''}`}
        style={{
          // Fix paper to exact physical A4/F4 dimensions so QR coordinates are stable across zoom
          width: paperSize === 'F4' ? '215mm' : '210mm',
          minHeight: paperSize === 'F4' ? '330mm' : '297mm',
          boxSizing: 'border-box',
          color: '#000000',
          paddingTop: `${effectiveTopMargin}cm`,
          paddingBottom: `${effectiveBottomMargin}cm`,
          paddingLeft: `${marginLeft}cm`,
          paddingRight: `${marginRight}cm`,
          position: 'relative',
          display: 'flex',
          flexDirection: 'column'
        }}
      >
        {isIkiLetterhead && (
          <div 
            className="absolute top-0 left-0 right-0 select-none iki-header" 
            style={{
              padding: '30px 30px 10px 30px',
              boxSizing: 'border-box'
            }}
            contentEditable={false}
          >
            <img src={customKopAtas || "/kop-atas.jpg"} alt="Kop Surat Atas IKI" className="w-full h-auto object-contain" />
          </div>
        )}

        {isLetterheadMode && (
          <div
            className="absolute top-0 left-0 right-0 border-b border-dashed border-blue-400 bg-blue-50/20 text-blue-700 text-xs font-black flex flex-col items-center justify-center select-none print:hidden z-20 pointer-events-none"
            style={{
              height: `${letterheadHeight}cm`,
              paddingTop: `${marginTop}cm`
            }}
          >
            <span className="bg-blue-650 text-white px-2.5 py-0.5 rounded text-[9.5px] uppercase tracking-wider font-extrabold shadow-sm mb-1.5">
              Kertas Berkop Fisik Aktif
            </span>
            <span className="text-[10px] opacity-75 font-semibold">
              Batas Area Kop Surat Fisik (Dikosongkan setinggi {letterheadHeight} cm ketika dicetak)
            </span>
          </div>
        )}

        <div
          ref={editorRef}
          contentEditable={!showPreviewMode}
          onInput={handleInput}
          onBlur={saveSelection}
          onKeyUp={saveSelection}
          onMouseUp={() => {
            saveSelection();
            applyCopiedFormat();
          }}
          onFocus={saveSelection}
          className="outline-none w-full text-justify animate-none flex-1 document-editor-content"
          style={{
            fontFamily: fontFamily,
            fontSize: fontSize,
            lineHeight: lineHeight,
            color: '#000000',
            cursor: isFormatPainterActive ? 'copy' : 'text',
            minHeight: '0',
            flex: '1 1 auto'
          }}
        />

        {/* Dynamic Footnotes for Approved Steps */}
        {documentData?.signatureFlow && documentData.signatureFlow.some(s => s.type === 'paraf' && s.status === 'approved') && (
          <div 
            className="mt-6 border-t border-slate-200 pt-2 select-none text-[9.5px] italic text-slate-500 font-semibold"
            style={{ fontFamily: fontFamily || 'sans-serif' }}
            contentEditable={false}
          >
            {documentData.signatureFlow
              .filter(s => s.type === 'paraf' && s.status === 'approved')
              .map(s => (
                <div key={s.id} className="leading-relaxed">
                  * Telah diparaf oleh {s.role} ({s.name}) pada {s.signedAt ? new Date(s.signedAt).toLocaleString('id-ID', {
                    day: 'numeric',
                    month: 'short',
                    year: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                  }) : ''}
                </div>
              ))
            }
          </div>
        )}

        {/* Absolute TTD QR Code Overlay — positioned using mm units (PDF coordinate system) */}
        {documentData?.isSigned && documentData.signatureX !== undefined && documentData.signatureY !== undefined && (() => {
          const paperW = paperSize === 'F4' ? 215 : 210;
          const paperH = paperSize === 'F4' ? 330 : 297;
          const xMm = (documentData.signatureX / 100) * paperW;
          const yMm = (documentData.signatureY / 100) * paperH;
          return (
            <div 
              className="absolute select-none z-30 flex flex-col items-center justify-center print:block print:absolute"
              style={{
                // Using mm units: stable across all browser zoom levels, matches PDF output exactly
                left: `${xMm}mm`,
                top: `${yMm}mm`,
                transform: 'translate(-50%, -50%)',
                width: '21mm',
                height: '24mm',
              }}
              contentEditable={false}
            >
              <img 
                src={`https://api.qrserver.com/v1/create-qr-code/?size=70x70&data=${encodeURIComponent(
                  window.location.origin + '/?verify=' + documentData.id
                )}`}
                alt="QR Code TTD"
                style={{ width: '18mm', height: '18mm', border: '1px solid #e2e8f0', background: '#fff', padding: '1px', objectFit: 'contain' }}
              />
              <div style={{ fontSize: '1.6mm', color: '#475569', fontWeight: 700, textAlign: 'center', marginTop: '1px', maxWidth: '21mm', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                Ttd {documentData.signatureFlow?.[documentData.signatureFlow.length - 1]?.name}
              </div>
            </div>
          );
        })()}

        {isIkiLetterhead && (
          <div 
            className="absolute bottom-0 left-0 right-0 select-none iki-footer" 
            style={{
              padding: '10px 30px 30px 30px',
              boxSizing: 'border-box'
            }}
            contentEditable={false}
          >
            <img src={customKopBawah || "/kop-bawah.jpg"} alt="Kop Surat Bawah IKI" className="w-full h-auto object-contain" />
          </div>
        )}
      </div>
    </>
  );
}
