'use client';

import { useRef, useState } from 'react';

export default function Pagina() {
  const inputRef = useRef<HTMLInputElement>(null);
  const [trascinando, setTrascinando] = useState(false);
  const [generazione, setGenerazione] = useState(false);
  const [errore, setErrore] = useState<string | null>(null);

  async function genera(file: File) {
    if (generazione) return;
    setErrore(null);
    if (!file.name.toLowerCase().endsWith('.xml')) {
      setErrore('Seleziona un file .xml di Fattura Elettronica.');
      return;
    }
    setGenerazione(true);
    try {
      const dati = new FormData();
      dati.append('file', file);
      const risposta = await fetch('/api/genera-pdf', { method: 'POST', body: dati });
      if (!risposta.ok) {
        const corpo = await risposta.json().catch(() => null);
        setErrore(corpo?.errore ?? 'Errore durante la generazione del PDF.');
        return;
      }
      const nome =
        risposta.headers.get('Content-Disposition')?.match(/filename="(.+)"/)?.[1] ??
        'Fattura.pdf';
      const url = URL.createObjectURL(await risposta.blob());
      const collegamento = document.createElement('a');
      collegamento.href = url;
      collegamento.download = nome;
      collegamento.click();
      URL.revokeObjectURL(url);
    } catch {
      setErrore('Errore di rete durante la generazione del PDF.');
    } finally {
      setGenerazione(false);
    }
  }

  return (
    <main>
      <h1>Fattura XML → PDF</h1>
      <p className="sottotitolo">
        Carica la Fattura Elettronica (.xml) e scarica la fattura di cortesia in PDF.
      </p>
      <div
        className={`zona${trascinando ? ' attiva' : ''}`}
        onClick={() => inputRef.current?.click()}
        onDragOver={(e) => {
          e.preventDefault();
          setTrascinando(true);
        }}
        onDragLeave={() => setTrascinando(false)}
        onDrop={(e) => {
          e.preventDefault();
          setTrascinando(false);
          const file = e.dataTransfer.files[0];
          if (file) genera(file);
        }}
      >
        Trascina qui il file .xml
        <br />
        oppure clicca per sceglierlo
      </div>
      <input
        ref={inputRef}
        type="file"
        accept=".xml,text/xml"
        hidden
        onChange={(e) => {
          const file = e.target.files?.[0];
          if (file) genera(file);
          e.target.value = '';
        }}
      />
      {generazione && <p className="stato">Generazione del PDF in corso…</p>}
      {errore && <p className="errore">{errore}</p>}
    </main>
  );
}
