import React, { useState, useEffect, useRef } from 'react';
import { Loader2, X, Printer } from 'lucide-react';
import { CustomFormPdfExport } from './CustomFormPdfExport';

// Tiny inline toast — no shadcn dependency
function useToast() {
  const [message, setMessage] = useState(null);
  const show = ({ variant, title, description }) => {
    setMessage({ variant, title, description });
    setTimeout(() => setMessage(null), 4000);
  };
  const ToastEl = message ? (
    <div className={`fixed bottom-6 right-6 z-[100] px-5 py-3 rounded-xl shadow-lg text-sm max-w-xs ${message.variant === 'destructive' ? 'bg-red-600 text-white' : 'bg-slate-900 text-white'}`}>
      <p className="font-semibold">{message.title}</p>
      {message.description && <p className="opacity-80 mt-0.5">{message.description}</p>}
    </div>
  ) : null;
  return { toast: show, ToastEl };
}

export function CustomFormPrintPreview({
  formConfig, sampleData, onClose, formName, autoPrint = false, onPrinted,
}) {
  const { toast, ToastEl } = useToast();
  const [pdfUrl, setPdfUrl] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const exportRef = useRef(null);

  useEffect(() => {
    let mounted = true;

    const generate = async () => {
      if (!exportRef.current) return;
      try {
        const blob = await exportRef.current.generatePdf(formName, true, true);
        if (mounted && blob) {
          setPdfUrl(URL.createObjectURL(blob));
          setIsLoading(false);
        }
      } catch (e) {
        console.error('Preview Generation Error', e);
        if (mounted) {
          setIsLoading(false);
          toast({ variant: 'destructive', title: 'Preview Failed', description: 'Could not generate PDF preview.' });
        }
      }
    };

    const timer = setTimeout(generate, 500);
    return () => {
      mounted = false;
      clearTimeout(timer);
    };
  }, [formName, formConfig, sampleData]);

  return (
    <div className="fixed inset-0 z-50 bg-slate-900/90 backdrop-blur-sm flex flex-col">
      {ToastEl}

      {/* Header bar */}
      <div className="bg-white border-b border-slate-200 px-6 py-4 flex items-center justify-between shadow-sm shrink-0">
        <div className="flex items-center gap-3">
          <div className="bg-slate-100 p-2 rounded-full">
            <Printer className="w-5 h-5 text-slate-700" />
          </div>
          <div>
            <h2 className="text-lg font-semibold text-slate-900">Print Preview</h2>
            <p className="text-xs text-slate-500">PDF Rendering</p>
          </div>
        </div>
        <button
          onClick={onClose}
          className="inline-flex items-center gap-2 h-9 px-4 rounded-lg border border-slate-200 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
        >
          <X className="w-4 h-4" /> Close
        </button>
      </div>

      {/* Content area */}
      <div className="flex-1 bg-slate-100 p-4 flex items-center justify-center overflow-hidden">
        {isLoading ? (
          <div className="flex flex-col items-center justify-center text-slate-400">
            <Loader2 className="w-8 h-8 animate-spin mb-4" />
            <p>Generating PDF Preview…</p>
          </div>
        ) : pdfUrl ? (
          <iframe
            src={pdfUrl}
            className="w-full h-full rounded shadow-lg border border-slate-300"
            title="PDF Preview"
          />
        ) : (
          <div className="text-red-500">Failed to load preview.</div>
        )}
      </div>

      {/* Hidden export engine */}
      <div className="hidden">
        <CustomFormPdfExport
          ref={exportRef}
          formConfig={formConfig}
          sampleData={sampleData}
          borderSettings={formConfig?.borderSettings}
        />
      </div>
    </div>
  );
}

export default CustomFormPrintPreview;
