"use client";

import { useState, useEffect, useRef } from "react";
import type { Article } from "@/src/types/article";
import type { Stabilimento, Magazzino } from "@/src/types/stabilimento";
import type { TipoMovimento } from "@/src/types/movimento";
import type { MacchinaWithDetails } from "@/src/types/macchina";
import DestinazioneModal from "./DestinazioneModal";

interface MovimentoModalProps {
  article: Article;
  tipo: TipoMovimento;
  onClose: () => void;
  onSuccess: () => void;
}

export default function MovimentoModal({
  article,
  tipo,
  onClose,
  onSuccess,
}: MovimentoModalProps) {
  const modalRef = useRef<HTMLDivElement>(null);
  const isCarico = tipo === "carico";

  const [stabilimenti, setStabilimenti] = useState<Stabilimento[]>([]);
  const [magazzini, setMagazzini] = useState<Magazzino[]>([]);
  const [selectedStabilimento, setSelectedStabilimento] = useState<number | null>(null);
  const [selectedMagazzino, setSelectedMagazzino] = useState<number | null>(null);
  const [quantita, setQuantita] = useState<number>(1);
  const [causale, setCausale] = useState<string>("");

  const [selectedDestinazione, setSelectedDestinazione] = useState<MacchinaWithDetails | null>(null);
  const [showDestinazioneModal, setShowDestinazioneModal] = useState(false);

  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchData() {
      if (!isCarico) return;
      
      try {
        const [stabRes, magRes] = await Promise.all([
          fetch("/api/stabilimenti"),
          fetch("/api/magazzini"),
        ]);

        if (stabRes.ok && magRes.ok) {
          const stabData = await stabRes.json();
          const magData = await magRes.json();
          setStabilimenti(stabData.stabilimenti);
          setMagazzini(magData.magazzini);
        }
      } catch (error) {
        console.error("Errore caricamento dati:", error);
      }
    }

    fetchData();
  }, [isCarico]);

  useEffect(() => {
    function handleKeyDown(e: KeyboardEvent) {
      if (e.key === "Escape" && !showDestinazioneModal) {
        onClose();
      }
    }

    document.addEventListener("keydown", handleKeyDown);

    return () => {
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [onClose, showDestinazioneModal]);

  const filteredMagazzini = selectedStabilimento
    ? magazzini.filter((m) => m.id_stabilimento === selectedStabilimento)
    : [];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (isCarico) {
      if (!selectedMagazzino) {
        setError("Seleziona un magazzino");
        return;
      }
    } else {
      if (!selectedDestinazione) {
        setError("Seleziona una destinazione (macchina/parte)");
        return;
      }
    }

    if (quantita <= 0) {
      setError("La quantità deve essere maggiore di zero");
      return;
    }

    if (!isCarico && quantita > article.quantita) {
      setError(`Quantità richiesta (${quantita}) supera la giacenza disponibile (${article.quantita})`);
      return;
    }

    setSaving(true);

    try {
      if (isCarico) {
        const res = await fetch("/api/movimenti", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            id_articolo: article.id,
            quantita,
            tipo,
            id_magazzino: selectedMagazzino,
            causale: causale || undefined,
          }),
        });

        if (!res.ok) {
          const data = await res.json();
          throw new Error(data.error || "Errore durante la registrazione");
        }
      } else {
        const res = await fetch("/api/art-macchine-parti/assegna", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            idart: article.id,
            idmacchina: selectedDestinazione!.id,
            quantita,
            causale: causale || `Scarico verso ${selectedDestinazione!.nome}`,
          }),
        });

        if (!res.ok) {
          const data = await res.json();
          throw new Error(data.error || "Errore durante l'assegnazione");
        }
      }

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

  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget && !showDestinazioneModal) {
      onClose();
    }
  };

  return (
    <div 
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm"
      onClick={handleBackdropClick}
    >
      <div
        ref={modalRef}
        className="w-full max-w-md bg-zinc-900 rounded-2xl shadow-2xl border border-zinc-800 overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className={`flex items-center justify-between px-6 py-4 border-b ${
          isCarico ? "border-green-500/30 bg-green-500/5" : "border-red-500/30 bg-red-500/5"
        }`}>
          <div className="flex items-center gap-3">
            <div className={`p-2 rounded-lg ${isCarico ? "bg-green-500/20 text-green-400" : "bg-red-500/20 text-red-400"}`}>
              {isCarico ? (
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                </svg>
              ) : (
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
                </svg>
              )}
            </div>
            <div>
              <h2 className={`text-lg font-semibold ${isCarico ? "text-green-400" : "text-red-400"}`}>
                {isCarico ? "Carico" : "Scarico"}
              </h2>
              <p className="text-xs text-zinc-500">Registra movimento</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800 transition-colors"
          >
            <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>

        {/* Articolo info */}
        <div className="px-6 py-3 bg-zinc-800/50 border-b border-zinc-800">
          <p className="text-sm text-zinc-400">Articolo</p>
          <p className="font-medium text-white">{article.descrizione}</p>
          <p className="text-xs text-zinc-500 font-mono">{article.codice}</p>
          <p className="text-xs text-zinc-500 mt-1">
            Giacenza attuale: <span className="text-white">{article.quantita}</span>
          </p>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          {error && (
            <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/50 text-red-400 text-sm">
              {error}
            </div>
          )}

          {/* Sezione CARICO: Stabilimento e Magazzino */}
          {isCarico && (
            <>
              <div>
                <label className="block text-sm font-medium text-zinc-400 mb-1">
                  Stabilimento
                </label>
                <select
                  value={selectedStabilimento ?? ""}
                  onChange={(e) => {
                    setSelectedStabilimento(e.target.value ? parseInt(e.target.value, 10) : null);
                    setSelectedMagazzino(null);
                  }}
                  className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white focus:outline-none focus:border-blue-500 transition-colors"
                >
                  <option value="">Seleziona stabilimento...</option>
                  {stabilimenti.map((stab) => (
                    <option key={stab.id} value={stab.id}>
                      {stab.descrizione}
                    </option>
                  ))}
                </select>
              </div>

              {selectedStabilimento && (
                <div>
                  <label className="block text-sm font-medium text-zinc-400 mb-1">
                    Magazzino (destinazione)
                  </label>
                  <select
                    value={selectedMagazzino ?? ""}
                    onChange={(e) => setSelectedMagazzino(e.target.value ? parseInt(e.target.value, 10) : null)}
                    className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white focus:outline-none focus:border-blue-500 transition-colors"
                  >
                    <option value="">Seleziona magazzino...</option>
                    {filteredMagazzini.map((mag) => (
                      <option key={mag.id} value={mag.id}>
                        {mag.descrizione}
                      </option>
                    ))}
                  </select>
                </div>
              )}
            </>
          )}

          {/* Sezione SCARICO: Destinazione Macchina/Parte */}
          {!isCarico && (
            <div>
              <label className="block text-sm font-medium text-zinc-400 mb-1">
                Destinazione (Macchina/Parte) <span className="text-red-400">*</span>
              </label>
              
              {selectedDestinazione ? (
                <div className="flex items-center justify-between p-3 rounded-lg bg-blue-900/20 border border-blue-700/50">
                  <div className="flex items-center gap-2">
                    <span className="text-lg">
                      {selectedDestinazione.tipo === "macchina" ? "🔧" : selectedDestinazione.tipo === "gruppo" ? "📁" : "⚙️"}
                    </span>
                    <span className="text-white font-medium">{selectedDestinazione.nome}</span>
                  </div>
                  <button
                    type="button"
                    onClick={() => setShowDestinazioneModal(true)}
                    className="px-3 py-1 text-xs rounded bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors"
                  >
                    Cambia
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={() => setShowDestinazioneModal(true)}
                  className="w-full px-4 py-3 rounded-lg bg-zinc-800 border-2 border-dashed border-zinc-600 text-zinc-400 hover:border-blue-500 hover:text-blue-400 transition-colors flex items-center justify-center gap-2"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                  </svg>
                  Seleziona Destinazione
                </button>
              )}
            </div>
          )}

          {/* Quantità */}
          <div>
            <label className="block text-sm font-medium text-zinc-400 mb-1">
              Quantità
            </label>
            <input
              type="number"
              value={quantita}
              onChange={(e) => setQuantita(parseFloat(e.target.value) || 0)}
              min="1"
              max={!isCarico ? article.quantita : undefined}
              className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white focus:outline-none focus:border-blue-500 transition-colors text-lg font-semibold"
            />
            {!isCarico && quantita > article.quantita && (
              <p className="mt-1 text-xs text-red-400">
                Quantità richiesta supera la giacenza disponibile ({article.quantita})
              </p>
            )}
          </div>

          {/* Causale */}
          <div>
            <label className="block text-sm font-medium text-zinc-400 mb-1">
              Causale {!isCarico && <span className="text-zinc-600">(opzionale)</span>}
            </label>
            <input
              type="text"
              value={causale}
              onChange={(e) => setCausale(e.target.value)}
              placeholder={isCarico ? "Es: Acquisto fornitore" : "Es: Manutenzione programmata"}
              className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-blue-500 transition-colors"
            />
          </div>

          {/* Actions */}
          <div className="flex justify-end gap-3 pt-4 border-t border-zinc-800">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800 transition-colors"
            >
              Annulla
            </button>
            <button
              type="submit"
              disabled={saving || (isCarico ? !selectedMagazzino : !selectedDestinazione)}
              className={`px-6 py-2 rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 ${
                isCarico 
                  ? "bg-green-600 text-white hover:bg-green-500" 
                  : "bg-red-600 text-white hover:bg-red-500"
              }`}
            >
              {saving && (
                <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
              )}
              {isCarico ? "Registra Carico" : "Registra Scarico"}
            </button>
          </div>
        </form>
      </div>

      {/* Modal Selezione Destinazione */}
      <DestinazioneModal
        isOpen={showDestinazioneModal}
        onClose={() => setShowDestinazioneModal(false)}
        onSelect={(macchina) => {
          setSelectedDestinazione(macchina);
          setShowDestinazioneModal(false);
        }}
        selectedId={selectedDestinazione?.id}
      />
    </div>
  );
}
