import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Loader2, Printer, Download, AlertCircle, ChevronDown } from 'lucide-react';
import { CustomFormPdfExport } from './CustomFormPdfExport';
import { sanitizeRichTextHtml } from '@/lib/customFormHtmlSanitizer';

// ---------------------------------------------------------------------------
// Inline stub utilities — replace these with your real implementations if
// you have them in your Lovable project, or keep as-is for basic behavior.
// ---------------------------------------------------------------------------
const replaceVariables = (text, data) => {
  if (!text || !data) return text || '';
  return text.replace(/\{\{([\w.]+)\}\}/g, (_, key) => {
    const val = data[key];
    return val != null ? String(val) : `{{${key}}}`;
  });
};
const decodeHtmlEntities = (str) => {
  if (!str) return '';
  const el = document.createElement('div');
  el.innerHTML = str;
  return el.innerText;
};
const sanitizeHtml = (html) => sanitizeRichTextHtml(html || '');

const toPdfFileName = (fileName = 'form-export') => `${String(fileName).replace(/[^a-z0-9]/gi, '_').toLowerCase() || 'form_export'}.pdf`;

async function downloadPdfBlob(blob, fileName) {
  const { saveFile } = await import('@/lib/saveFile');
  await saveFile(blob, { suggestedName: toPdfFileName(fileName), mimeType: 'application/pdf', description: 'PDF Document' });
}

function openPdfBlob(blob, fileName) {
  const url = URL.createObjectURL(blob);
  const win = window.open(url, '_blank');

  if (win) {
    win.opener = null;
    setTimeout(() => URL.revokeObjectURL(url), 60000);
    return true;
  }

  downloadPdfBlob(blob, fileName);
  setTimeout(() => URL.revokeObjectURL(url), 60000);
  return false;
}

// Simple dropdown menu (replaces shadcn DropdownMenu)
function PrintMenu({ onVisualCapture, onIframePrint, onNativePrint, isCapturing }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const handler = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(o => !o)}
        disabled={isCapturing}
        className="inline-flex items-center gap-2 h-8 px-3 rounded-md border border-slate-200 bg-white text-sm text-slate-700 hover:bg-slate-50 shadow-sm disabled:opacity-50 transition-colors"
      >
        {isCapturing
          ? <Loader2 className="w-4 h-4 animate-spin" />
          : <Printer className="w-4 h-4" />}
        Print / Save
        <ChevronDown className="w-3 h-3 opacity-60" />
      </button>

      {open && (
        <div className="absolute right-0 top-9 z-50 w-52 bg-white border border-slate-200 rounded-lg shadow-lg overflow-hidden">
          <div className="px-3 py-2 text-[10px] font-semibold uppercase text-slate-400 border-b border-slate-100">
            Print Options
          </div>
          <button
            onClick={() => { setOpen(false); onVisualCapture(); }}
            disabled={isCapturing}
            className="flex items-center gap-2 w-full px-3 py-2.5 text-sm text-slate-700 hover:bg-slate-50 transition-colors"
          >
            <Download className="w-4 h-4" /> Save as PDF (Visual)
          </button>
          <button
            onClick={() => { setOpen(false); onIframePrint(); }}
            className="flex items-center gap-2 w-full px-3 py-2.5 text-sm text-slate-700 hover:bg-slate-50 transition-colors"
          >
            <Printer className="w-4 h-4" /> Print (Standard)
          </button>
          <button
            onClick={() => { setOpen(false); onNativePrint(); }}
            className="flex items-center gap-2 w-full px-3 py-2.5 text-sm text-slate-700 hover:bg-slate-50 transition-colors"
          >
            <AlertCircle className="w-4 h-4" /> Browser Print (Fallback)
          </button>
        </div>
      )}
    </div>
  );
}

export function CustomFormPreview({ formConfig, clientId, sampleData, mode = 'preview' }) {
  const { header, footer, blocks = [], borderSettings, globalSettings } = formConfig;
  const [resolvedData, setResolvedData] = useState(null);
  const [isCapturing, setIsCapturing] = useState(false);
  const exportRef = useRef(null);

  const effectiveSampleData = useMemo(() => sampleData || {}, [sampleData]);
  const pdfFileName = useMemo(() => formConfig?.name || 'form-export', [formConfig?.name]);

  // Resolve sample data (no Supabase — uses passed-in sampleData directly)
  useEffect(() => {
    const base = {
      propertyAddress: '123 Palm Tree Lane, Miami FL 33101',
      ownerName: 'John & Jane Doe',
      currentDate: new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }),
      pageNumber: '1',
      totalPages: '1',
      accountNumber: 'ACC-99823',
      currentBalance: '$450.00',
      clientName: 'Association Name',
      ...effectiveSampleData,
    };
    setResolvedData(base);
  }, [effectiveSampleData]);

  const processText = (text) => {
    if (!text || !resolvedData) return text || '';
    return sanitizeHtml(decodeHtmlEntities(replaceVariables(text, resolvedData)));
  };

  const generatePdfBlob = useCallback(async () => {
    if (!exportRef.current) throw new Error('PDF generator unavailable');
    const blob = await exportRef.current.generatePdf(pdfFileName, true, true);
    if (!blob) throw new Error('Could not generate PDF');
    return blob;
  }, [pdfFileName]);

  const handleVisualCapture = useCallback(async () => {
    try {
      setIsCapturing(true);
      downloadPdfBlob(await generatePdfBlob(), pdfFileName);
    } catch (err) {
      console.error('PDF Export Error:', err);
    } finally {
      setIsCapturing(false);
    }
  }, [generatePdfBlob, pdfFileName]);

  const handleIframePrint = useCallback(async () => {
    try {
      setIsCapturing(true);
      openPdfBlob(await generatePdfBlob(), pdfFileName);
    } catch (err) {
      console.error('Print Preview Error:', err);
    } finally {
      setIsCapturing(false);
    }
  }, [generatePdfBlob, pdfFileName]);

  const handleNativePrint = useCallback(() => {
    handleIframePrint();
  }, [handleIframePrint]);

  if (!resolvedData) {
    return (
      <div className="flex h-full items-center justify-center text-slate-400">
        <Loader2 className="w-6 h-6 animate-spin mr-2" /> Generating Preview…
      </div>
    );
  }

  const headerStyle = header?.styles || {};
  const footerStyle = footer?.styles || {};
  const certifiedMailNumber = resolvedData.certifiedMailNumber || '';

  const renderSafeFooterContent = (htmlContent) => {
    if (!htmlContent) return null;
    return <div className="whitespace-pre-wrap" dangerouslySetInnerHTML={{ __html: processText(htmlContent) }} />;
  };

  return (
    <div className={`flex flex-col items-center py-8 relative ${mode === 'preview' ? 'bg-slate-100/50 min-h-full overflow-y-auto' : 'bg-white'}`}>
      <style>{`
        .ql-indent-1 { padding-left: 2em; }
        .ql-indent-2 { padding-left: 4em; }
        .ql-indent-3 { padding-left: 6em; }
        .custom-form-rich-text p,
        .custom-form-rich-text > div,
        .custom-form-rich-text blockquote,
        .custom-form-rich-text pre {
          margin: 0 0 0.55em;
          line-height: 1.6;
        }
        .custom-form-rich-text p:last-child,
        .custom-form-rich-text > div:last-child,
        .custom-form-rich-text blockquote:last-child,
        .custom-form-rich-text pre:last-child {
          margin-bottom: 0;
        }
        .custom-form-rich-text ul { list-style-type: disc; padding-left: 2em; margin: 0.25em 0; }
        .custom-form-rich-text ol { list-style-type: decimal; padding-left: 2em; margin: 0.25em 0; }
        .custom-form-rich-text ol[start] { counter-reset: none; }
        .custom-form-rich-text li { margin: 0.15em 0; }
        .custom-form-rich-text table p,
        .custom-form-rich-text table div {
          margin: 0;
          line-height: 1.5;
        }
        hr { border-top: 1px solid #e2e8f0; margin: 1em 0; }
        @media print {
          @page { size: letter; margin: 0.6in; }
          body { margin: 0; padding: 0; }
          body > * { display: none !important; }
          #custom-form-preview-content {
            display: block !important;
            position: static !important;
            width: 100% !important;
            height: auto !important;
            min-height: 0 !important;
            margin: 0 !important;
            padding: 0 !important;
            transform: none !important;
            box-shadow: none !important;
            border: none !important;
            overflow: visible !important;
          }
          #custom-form-preview-content * { visibility: visible !important; }
          #custom-form-preview-content [data-print-hide] { display: none !important; }
          #custom-form-preview-content .mb-4 {
            page-break-inside: avoid;
            break-inside: avoid;
          }
          .page-break-marker {
            page-break-before: always;
            break-before: page;
            display: block;
            height: 0;
            visibility: hidden;
          }
        }
      `}</style>

      {/* Print/Save menu */}
      {mode === 'preview' && (
        <div className="absolute top-4 right-4 z-50" data-print-hide>
          <PrintMenu
            onVisualCapture={handleVisualCapture}
            onIframePrint={handleIframePrint}
            onNativePrint={handleNativePrint}
            isCapturing={isCapturing}
          />
        </div>
      )}

      {/* Page simulation */}
      <div
        id="custom-form-preview-content"
        className="bg-white shadow-2xl w-[8.5in] min-h-[11in] relative flex flex-col text-left"
        style={{
          padding: '0.75in',
          border: borderSettings?.enabled ? `1px solid ${borderSettings.color}` : 'none',
          boxSizing: 'border-box',
          fontFamily: globalSettings?.fontFamily || 'Helvetica, Arial, sans-serif',
        }}
      >
        {/* Header */}
        {header?.enabled && (
          <div className="relative w-full mb-5">
            <div
              className="pr-20 text-left"
              style={{ fontFamily: headerStyle.fontFamily || 'inherit' }}
            >
              {header.title && (
                <h1
                  className="leading-tight mb-2"
                  style={{
                    fontSize: headerStyle.fontSize ? `${headerStyle.fontSize}px` : '24px',
                    fontWeight: headerStyle.fontWeight === 'bold' ? 'bold' : 'normal',
                    color: headerStyle.textColor || '#000000',
                  }}
                  dangerouslySetInnerHTML={{ __html: processText(header.title) }}
                />
              )}
              {header.description && (
                <div
                  className="opacity-90 whitespace-pre-wrap text-sm"
                  style={{ color: headerStyle.textColor || '#000000' }}
                  dangerouslySetInnerHTML={{ __html: processText(header.description) }}
                />
              )}
            </div>
            {header.logoUrl && (
              <div className="absolute top-0 right-0">
                <img
                  src={header.logoUrl}
                  alt="Logo"
                  className="object-contain"
                  style={{
                    height: `${headerStyle.logoHeight || 60}px`,
                    width: headerStyle.logoWidth ? `${headerStyle.logoWidth}px` : 'auto',
                    maxWidth: '200px',
                  }}
                  crossOrigin="anonymous"
                />
              </div>
            )}
          </div>
        )}

        {/* Certified mail number */}
        {certifiedMailNumber && (
          <div className="mb-6 text-right text-slate-900" style={{ fontSize: '10pt' }}>
            <div className="font-bold italic underline">Sent via U.S. Certified Mail No.:</div>
            <div>{certifiedMailNumber}</div>
          </div>
        )}

        {/* Body content */}
        <div className="flex-1 custom-form-rich-text">
          {blocks.length === 0 ? (
            <div className="h-40 flex items-center justify-center text-slate-300 italic border-2 border-dashed border-slate-100 rounded" data-print-hide>
              Start adding sections to see preview…
            </div>
          ) : (
            blocks.map((block, i) => (
              <div
                key={block.id || i}
                className="mb-4"
                style={{ fontFamily: block.styles?.fontFamily || 'inherit' }}
                dangerouslySetInnerHTML={{ __html: processText(block.content || '') }}
              />
            ))
          )}
        </div>

        {/* Footer */}
        {footer?.enabled && (
          <div
            className="mt-auto pt-6 border-t border-slate-200 text-sm text-slate-500"
            style={{ fontFamily: footerStyle.fontFamily || 'inherit', marginTop: `${footerStyle.marginTop || 20}px` }}
          >
            <div style={{ textAlign: footerStyle.alignment || 'center' }}>
              {renderSafeFooterContent(footer.content)}
            </div>
            <div className="flex justify-between mt-2 text-[10px] opacity-70" data-print-hide>
              {footer.showDate ? <span>{resolvedData.currentDate}</span> : <span />}
              <span>{resolvedData?.clientName || ''}</span>
              <span>Confidential Information</span>
              {footer.showPageNumbers ? <span>Page 1</span> : <span />}
            </div>
          </div>
        )}
      </div>

      <div className="hidden">
        <CustomFormPdfExport
          ref={exportRef}
          formConfig={formConfig}
          sampleData={effectiveSampleData}
          borderSettings={borderSettings}
        />
      </div>
    </div>
  );
}

export default CustomFormPreview;
