'use client';

import { useState } from 'react';
import { Eye, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { apiFetch } from '@/lib/api/client';
import { TEMPLATE_VARIABLES } from '@/lib/pdf/tiptap-validation';

interface TemplatePreviewProps {
  content: Record<string, unknown> | null;
  templateName: string;
}

export function TemplatePreview({ content, templateName }: TemplatePreviewProps) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [pdfBase64, setPdfBase64] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  // Build sample data from TEMPLATE_VARIABLES examples
  const sampleData = Object.fromEntries(TEMPLATE_VARIABLES.map((v) => [v.key, v.example]));

  async function handlePreview() {
    if (!content) {
      setError('No content to preview.');
      setOpen(true);
      return;
    }

    setLoading(true);
    setError(null);
    setPdfBase64(null);
    setOpen(true);

    try {
      const res = await apiFetch<{ data: { pdfBase64: string } }>(
        '/api/v1/admin/templates/preview',
        {
          method: 'POST',
          body: { content, sampleData },
        },
      );
      setPdfBase64(res.data.pdfBase64);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Preview generation failed');
    } finally {
      setLoading(false);
    }
  }

  function handleOpenInNewTab() {
    if (!pdfBase64) return;
    const blob = base64ToBlob(pdfBase64, 'application/pdf');
    const url = URL.createObjectURL(blob);
    window.open(url, '_blank');
  }

  return (
    <>
      <Button variant="outline" size="sm" onClick={handlePreview}>
        <Eye className="mr-1.5 h-3.5 w-3.5" aria-hidden />
        Preview PDF
      </Button>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <div className="flex items-center justify-between">
              <DialogTitle>Preview - {templateName}</DialogTitle>
              {pdfBase64 && (
                <Button variant="ghost" size="sm" onClick={handleOpenInNewTab} className="mr-6">
                  <ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />
                  Open in new tab
                </Button>
              )}
            </div>
          </DialogHeader>

          <div className="mt-2 min-h-[60vh]">
            {loading && (
              <div className="flex h-60 items-center justify-center text-muted-foreground">
                <div className="text-center">
                  <div className="mb-2 h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto" />
                  <p className="text-sm">Generating preview…</p>
                </div>
              </div>
            )}

            {error && !loading && (
              <div className="rounded bg-destructive/10 p-4 text-sm text-destructive">{error}</div>
            )}

            {pdfBase64 && !loading && (
              <iframe
                src={`data:application/pdf;base64,${pdfBase64}`}
                className="h-[70vh] w-full rounded border"
                title={`Preview: ${templateName}`}
              />
            )}
          </div>

          <p className="text-xs text-muted-foreground">
            Preview uses sample values for all template variables.
          </p>
        </DialogContent>
      </Dialog>
    </>
  );
}

function base64ToBlob(base64: string, mimeType: string): Blob {
  const byteCharacters = atob(base64);
  const byteNumbers = new Uint8Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  return new Blob([byteNumbers], { type: mimeType });
}
