"use client";

import { useState, useEffect, useRef } from "react";
import type { Article, ArticleInput, ArticleFamily } from "@/src/types/article";
import type { Stabilimento, Magazzino } from "@/src/types/stabilimento";

interface ArticleModalProps {
  article: Article | null;
  families: ArticleFamily[];
  onClose: () => void;
  onSave: (article: Article) => void;
}

export default function ArticleModal({
  article,
  families,
  onClose,
  onSave,
}: ArticleModalProps) {
  const isEdit = article !== null;
  const modalRef = useRef<HTMLDivElement>(null);

  const [formData, setFormData] = useState<ArticleInput>({
    codice: "",
    descrizione: "",
    barcode: "",
    id_famiglia: null,
    id_magazzino: null,
    prezzo: 0,
    quantita_minima: 0,
    quantita: 0,
  });

  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 [quantitaIniziale, setQuantitaIniziale] = useState<number>(0);

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

  useEffect(() => {
    if (article) {
      setFormData({
        codice: article.codice,
        descrizione: article.descrizione,
        barcode: article.barcode || "",
        id_famiglia: article.id_famiglia,
        id_magazzino: article.id_magazzino,
        prezzo: article.prezzo,
        quantita_minima: article.quantita_minima,
        quantita: 0,
      });
    }
  }, [article]);

  useEffect(() => {
    if (!isEdit) {
      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 stabilimenti/magazzini:", error);
        }
      }

      fetchData();
    }
  }, [isEdit]);

  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 (!isEdit && quantitaIniziale > 0 && !selectedMagazzino) {
      setError("Seleziona un magazzino per la giacenza iniziale");
      return;
    }

    setSaving(true);

    try {
      const url = isEdit ? `/api/articoli/${article.id}` : "/api/articoli";
      const method = isEdit ? "PUT" : "POST";

      const payload = {
        ...formData,
        id_magazzino: selectedMagazzino,
        quantita: quantitaIniziale,
      };

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

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

      const data = await res.json();
      onSave(data.article);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Errore sconosciuto");
    } finally {
      setSaving(false);
    }
  };

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>
  ) => {
    const { name, value, type } = e.target;

    setFormData((prev) => ({
      ...prev,
      [name]:
        type === "number"
          ? value === "" ? 0 : parseFloat(value)
          : name === "id_famiglia"
            ? value === "" ? null : parseInt(value, 10)
            : value,
    }));
  };

  const handleStabilimentoChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value ? parseInt(e.target.value, 10) : null;
    setSelectedStabilimento(value);
    setSelectedMagazzino(null);
  };

  const handleMagazzinoChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value ? parseInt(e.target.value, 10) : null;
    setSelectedMagazzino(value);
  };

  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-lg bg-zinc-900 rounded-2xl shadow-2xl border border-zinc-800 overflow-hidden max-h-[90vh] flex flex-col"
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-zinc-800 flex-shrink-0">
          <h2 className="text-xl font-semibold text-white">
            {isEdit ? "Modifica Articolo" : "Nuovo Articolo"}
          </h2>
          <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>

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

          {/* Descrizione */}
          <div>
            <label className="block text-sm font-medium text-zinc-400 mb-1">
              Descrizione *
            </label>
            <input
              type="text"
              name="descrizione"
              value={formData.descrizione}
              onChange={handleChange}
              required
              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"
              placeholder="Nome dell'articolo"
            />
          </div>

          {/* Codice e Barcode */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-zinc-400 mb-1">
                Codice
              </label>
              <input
                type="text"
                name="codice"
                value={formData.codice}
                onChange={handleChange}
                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 font-mono"
                placeholder="Auto-generato"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-zinc-400 mb-1">
                Barcode
              </label>
              <input
                type="text"
                name="barcode"
                value={formData.barcode || ""}
                onChange={handleChange}
                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 font-mono"
                placeholder="Codice a barre"
              />
            </div>
          </div>

          {/* Famiglia */}
          <div>
            <label className="block text-sm font-medium text-zinc-400 mb-1">
              Famiglia
            </label>
            <select
              name="id_famiglia"
              value={formData.id_famiglia ?? ""}
              onChange={handleChange}
              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="">Nessuna famiglia</option>
              {families.map((fam) => (
                <option key={fam.id} value={fam.id}>
                  {fam.nome}
                </option>
              ))}
            </select>
          </div>

          {/* Prezzo e Quantità minima */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-zinc-400 mb-1">
                Prezzo (€)
              </label>
              <input
                type="number"
                name="prezzo"
                value={formData.prezzo}
                onChange={handleChange}
                min="0"
                step="0.01"
                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>
            <div>
              <label className="block text-sm font-medium text-zinc-400 mb-1">
                Quantità minima
              </label>
              <input
                type="number"
                name="quantita_minima"
                value={formData.quantita_minima}
                onChange={handleChange}
                min="0"
                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>
          </div>

          {/* Giacenza iniziale (solo per nuovo articolo) */}
          {!isEdit && (
            <div className="p-4 rounded-lg bg-green-500/5 border border-green-500/30">
              <h3 className="text-sm font-semibold text-green-400 mb-3 flex items-center gap-2">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
                </svg>
                Giacenza iniziale
              </h3>
              
              <div className="space-y-3">
                {/* Stabilimento */}
                <div>
                  <label className="block text-xs font-medium text-zinc-500 mb-1">
                    Stabilimento
                  </label>
                  <select
                    value={selectedStabilimento ?? ""}
                    onChange={handleStabilimentoChange}
                    className="w-full px-3 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-sm focus:outline-none focus:border-green-500 transition-colors"
                  >
                    <option value="">Seleziona stabilimento...</option>
                    {stabilimenti.map((stab) => (
                      <option key={stab.id} value={stab.id}>
                        {stab.descrizione}
                      </option>
                    ))}
                  </select>
                </div>

                {/* Magazzino (visibile solo se stabilimento selezionato) */}
                {selectedStabilimento && (
                  <div>
                    <label className="block text-xs font-medium text-zinc-500 mb-1">
                      Magazzino
                    </label>
                    <select
                      value={selectedMagazzino ?? ""}
                      onChange={handleMagazzinoChange}
                      className="w-full px-3 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-sm focus:outline-none focus:border-green-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-xs font-medium text-zinc-500 mb-1">
                    Quantità
                  </label>
                  <input
                    type="number"
                    value={quantitaIniziale}
                    onChange={(e) => setQuantitaIniziale(parseFloat(e.target.value) || 0)}
                    min="0"
                    className="w-full px-3 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-sm focus:outline-none focus:border-green-500 transition-colors"
                    placeholder="0"
                  />
                </div>

                {quantitaIniziale > 0 && !selectedMagazzino && (
                  <p className="text-xs text-yellow-400">
                    Seleziona un magazzino per registrare la giacenza iniziale
                  </p>
                )}
              </div>
            </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}
              className="px-6 py-2 rounded-lg bg-blue-600 text-white font-medium hover:bg-blue-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                </svg>
              )}
              {isEdit ? "Salva modifiche" : "Crea articolo"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
