"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";

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 [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchData() {
      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();
  }, []);

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

    function handleClickOutside(e: MouseEvent) {
      if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
        onClose();
      }
    }

    document.addEventListener("keydown", handleKeyDown);
    document.addEventListener("mousedown", handleClickOutside);

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

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

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

    if (!selectedMagazzino) {
      setError("Seleziona un magazzino");
      return;
    }

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

    setSaving(true);

    try {
      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");
      }

      onSuccess();
    } 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 bg-black/70 backdrop-blur-sm">
      <div
        ref={modalRef}
        className="w-full max-w-md bg-zinc-900 rounded-2xl shadow-2xl border border-zinc-800 overflow-hidden"
      >
        {/* 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>
          )}

          {/* Stabilimento */}
          <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>

          {/* Magazzino */}
          {selectedStabilimento && (
            <div>
              <label className="block text-sm font-medium text-zinc-400 mb-1">
                Magazzino {isCarico ? "(destinazione)" : "(origine)"}
              </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>
          )}

          {/* 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"
              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"
            />
          </div>

          {/* Causale */}
          <div>
            <label className="block text-sm font-medium text-zinc-400 mb-1">
              Causale (opzionale)
            </label>
            <input
              type="text"
              value={causale}
              onChange={(e) => setCausale(e.target.value)}
              placeholder={isCarico ? "Es: Acquisto fornitore" : "Es: Utilizzo manutenzione"}
              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 || !selectedMagazzino}
              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>
    </div>
  );
}
