"use client";

import { useState } from "react";
import type { ArticoloAssegnatoMacchina } from "@/src/types/artMacchineParti";

interface ArticoliMacchinaModalProps {
  macchinaId: number;
  macchinaNome: string;
  articoli: ArticoloAssegnatoMacchina[];
  onClose: () => void;
  onArticoloRimosso: () => void;
}

interface RimuoviModalState {
  articolo: ArticoloAssegnatoMacchina;
  quantita: number;
  opzione: "carico" | "elimina";
}

export default function ArticoliMacchinaModal({
  macchinaId,
  macchinaNome,
  articoli,
  onClose,
  onArticoloRimosso,
}: ArticoliMacchinaModalProps) {
  const [rimuoviModal, setRimuoviModal] = useState<RimuoviModalState | null>(null);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleRimuoviClick = (articolo: ArticoloAssegnatoMacchina) => {
    setRimuoviModal({
      articolo,
      quantita: 1,
      opzione: "carico",
    });
    setError(null);
  };

  const handleConfermaRimozione = async () => {
    if (!rimuoviModal) return;

    setSaving(true);
    setError(null);

    try {
      const res = await fetch(
        `/api/art-macchine-parti/${macchinaId}/${rimuoviModal.articolo.id_articolo}`,
        {
          method: "DELETE",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            quantita: rimuoviModal.quantita,
            opzione: rimuoviModal.opzione,
          }),
        }
      );

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Errore nella rimozione");
      }

      setRimuoviModal(null);
      onArticoloRimosso();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Errore sconosciuto");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
      <div className="relative w-full max-w-lg max-h-[80vh] bg-zinc-900 rounded-xl border border-zinc-800 shadow-2xl flex flex-col">
        <div className="flex items-center justify-between px-5 py-4 border-b border-zinc-800 bg-teal-900/20">
          <div>
            <h3 className="text-lg font-semibold text-white">Articoli Assegnati</h3>
            <p className="text-xs text-zinc-500">{macchinaNome}</p>
          </div>
          <button
            onClick={onClose}
            className="p-1 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-4">
          {articoli.length === 0 ? (
            <div className="text-center py-8 text-zinc-500">
              Nessun articolo assegnato
            </div>
          ) : (
            <div className="space-y-2">
              {articoli.map((art) => (
                <div
                  key={`${art.id_articolo}-${art.id}`}
                  className="flex items-center justify-between p-3 rounded-lg bg-zinc-800/50 border border-zinc-700 group"
                >
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-white truncate">{art.descrizione}</p>
                    <p className="text-xs text-zinc-500 font-mono">{art.codice}</p>
                  </div>
                  <div className="flex items-center gap-3">
                    <div className="text-right">
                      <div className="text-lg font-bold text-teal-400">{art.quantita}</div>
                      <div className="text-[10px] text-zinc-600">assegnati</div>
                    </div>
                    <button
                      onClick={() => handleRimuoviClick(art)}
                      className="p-2 rounded-lg text-zinc-500 hover:text-red-400 hover:bg-red-900/20 opacity-0 group-hover:opacity-100 transition-opacity"
                      title="Rimuovi articolo"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="px-5 py-3 border-t border-zinc-800 bg-zinc-900/50 flex justify-between items-center">
          <span className="text-xs text-zinc-500">
            Totale: {articoli.reduce((sum, a) => sum + a.quantita, 0)} pezzi in {articoli.length} articoli
          </span>
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-zinc-300 hover:text-white rounded-lg hover:bg-zinc-800"
          >
            Chiudi
          </button>
        </div>
      </div>

      {/* Modal conferma rimozione */}
      {rimuoviModal && (
        <div className="fixed inset-0 z-60 flex items-center justify-center">
          <div className="absolute inset-0 bg-black/60" onClick={() => !saving && setRimuoviModal(null)} />
          <div className="relative w-full max-w-md bg-zinc-900 rounded-xl border border-zinc-800 shadow-2xl">
            <div className="px-5 py-4 border-b border-zinc-800 bg-red-900/20">
              <h3 className="text-lg font-semibold text-white">Rimuovi Articolo</h3>
              <p className="text-xs text-zinc-500">{rimuoviModal.articolo.descrizione}</p>
            </div>

            <div className="p-5 space-y-4">
              {error && (
                <div className="p-3 rounded-lg bg-red-900/30 border border-red-800 text-red-400 text-sm">
                  {error}
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-zinc-300 mb-2">
                  Quantità da rimuovere (max: {rimuoviModal.articolo.quantita})
                </label>
                <input
                  type="number"
                  min={1}
                  max={rimuoviModal.articolo.quantita}
                  value={rimuoviModal.quantita}
                  onChange={(e) =>
                    setRimuoviModal({
                      ...rimuoviModal,
                      quantita: Math.min(
                        Math.max(1, parseInt(e.target.value) || 1),
                        rimuoviModal.articolo.quantita
                      ),
                    })
                  }
                  className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-teal-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-zinc-300 mb-2">
                  Cosa fare con gli articoli rimossi?
                </label>
                <div className="space-y-2">
                  <label className="flex items-center gap-3 p-3 rounded-lg bg-zinc-800 border border-zinc-700 cursor-pointer hover:border-teal-600">
                    <input
                      type="radio"
                      name="opzione"
                      value="carico"
                      checked={rimuoviModal.opzione === "carico"}
                      onChange={() => setRimuoviModal({ ...rimuoviModal, opzione: "carico" })}
                      className="w-4 h-4 text-teal-500"
                    />
                    <div>
                      <p className="text-sm font-medium text-white">Rientra in magazzino</p>
                      <p className="text-xs text-zinc-500">Gli articoli torneranno disponibili nel magazzino</p>
                    </div>
                  </label>
                  <label className="flex items-center gap-3 p-3 rounded-lg bg-zinc-800 border border-zinc-700 cursor-pointer hover:border-red-600">
                    <input
                      type="radio"
                      name="opzione"
                      value="elimina"
                      checked={rimuoviModal.opzione === "elimina"}
                      onChange={() => setRimuoviModal({ ...rimuoviModal, opzione: "elimina" })}
                      className="w-4 h-4 text-red-500"
                    />
                    <div>
                      <p className="text-sm font-medium text-white">Elimina definitivamente</p>
                      <p className="text-xs text-zinc-500">Gli articoli saranno rimossi senza rientro</p>
                    </div>
                  </label>
                </div>
              </div>
            </div>

            <div className="px-5 py-4 border-t border-zinc-800 flex justify-end gap-3">
              <button
                onClick={() => setRimuoviModal(null)}
                disabled={saving}
                className="px-4 py-2 text-sm font-medium text-zinc-300 hover:text-white rounded-lg hover:bg-zinc-800 disabled:opacity-50"
              >
                Annulla
              </button>
              <button
                onClick={handleConfermaRimozione}
                disabled={saving}
                className="px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-lg disabled:opacity-50 flex items-center gap-2"
              >
                {saving ? (
                  <>
                    <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                    </svg>
                    Rimozione...
                  </>
                ) : (
                  "Conferma rimozione"
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
