'use client';

import { useMemo, useRef, useState } from 'react';
import { Download, ZoomIn, ZoomOut, Copy } from 'lucide-react';
import { Button } from '@/shared/components/ui/button';
import type { SignatureConfig } from '../types';
import { generateSignatureHtml, downloadSignatureHtml } from '../services/signature-builder';

const ZOOM_LEVELS = [0.75, 1, 1.5, 2, 2.5];

interface SignaturePreviewProps {
  config: SignatureConfig;
}

export function SignaturePreview({ config }: SignaturePreviewProps) {
  const [zoomIndex, setZoomIndex] = useState(1); // start at 100%
  const [copied, setCopied] = useState(false);
  const previewRef = useRef<HTMLDivElement>(null);

  const zoom = ZOOM_LEVELS[zoomIndex] ?? 1;

  const html = useMemo(() => generateSignatureHtml(config), [config]);

  const handleDownload = () => {
    const filename = `semnatura-${config.company}-${config.name.toLowerCase().replace(/\s+/g, '-') || 'email'}.html`;
    downloadSignatureHtml(html, filename);
  };

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(html);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // fallback
    }
  };

  const zoomIn = () => setZoomIndex((i) => Math.min(i + 1, ZOOM_LEVELS.length - 1));
  const zoomOut = () => setZoomIndex((i) => Math.max(i - 1, 0));

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Previzualizare</h2>
        <div className="flex items-center gap-2">
          <div className="flex items-center rounded-md border">
            <Button variant="ghost" size="icon" className="h-8 w-8 rounded-r-none" onClick={zoomOut} disabled={zoomIndex <= 0}>
              <ZoomOut className="h-4 w-4" />
            </Button>
            <span className="w-14 text-center text-sm font-medium">{Math.round(zoom * 100)}%</span>
            <Button variant="ghost" size="icon" className="h-8 w-8 rounded-l-none" onClick={zoomIn} disabled={zoomIndex >= ZOOM_LEVELS.length - 1}>
              <ZoomIn className="h-4 w-4" />
            </Button>
          </div>
          <Button variant="outline" size="sm" onClick={handleCopy}>
            <Copy className="mr-1 h-4 w-4" />
            {copied ? 'Copiat!' : 'Copiază HTML'}
          </Button>
          <Button size="sm" onClick={handleDownload}>
            <Download className="mr-1 h-4 w-4" />
            Descarcă HTML
          </Button>
        </div>
      </div>

      <div className="max-h-[calc(100vh-14rem)] overflow-auto rounded-lg border bg-white p-6">
        <div
          ref={previewRef}
          style={{ transform: `scale(${zoom})`, transformOrigin: 'top left' }}
          className="transition-transform"
          dangerouslySetInnerHTML={{ __html: html }}
        />
      </div>
    </div>
  );
}
