"use client";

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

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

export default function ArticleModal({
  article,
  families,
  stabilimentoId,
  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 [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: article.quantita,
      });
    }
  }, [article]);

  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 handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSaving(true);

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

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

      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,
    }));
  };

  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"
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-zinc-800">
          <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">
          {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>

          {/* Quantità iniziale (solo per nuovo articolo) */}
          {!isEdit && (
            <div>
              <label className="block text-sm font-medium text-zinc-400 mb-1">
                Quantità iniziale
              </label>
              <input
                type="number"
                name="quantita"
                value={formData.quantita}
                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>
          )}

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