"use client";

import { useState, useEffect } from "react";
import type { MacchinaWithDetails, TipoMacchina } from "@/src/types/macchina";
import type { Stabilimento } from "@/src/types/stabilimento";

interface FormData {
  nome: string;
  tipo: TipoMacchina;
  id_stabilimento: string;
  colore_testo: string;
}

interface MacchinaModalProps {
  isOpen: boolean;
  editingMacchina: MacchinaWithDetails | null;
  stabilimenti: Stabilimento[];
  parentId: number | null;
  parentStabilimento: number | null;
  onClose: () => void;
  onConfirm: (data: FormData & { id_padre?: number | null }) => Promise<void>;
}

export default function MacchinaModal({
  isOpen,
  editingMacchina,
  stabilimenti,
  parentId,
  parentStabilimento,
  onClose,
  onConfirm,
}: MacchinaModalProps) {
  const [formData, setFormData] = useState<FormData>({
    nome: "",
    tipo: "macchina",
    id_stabilimento: "",
    colore_testo: "#3b82f6",
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const isEditing = !!editingMacchina?.id;

  useEffect(() => {
    if (isOpen) {
      if (isEditing && editingMacchina) {
        setFormData({
          nome: editingMacchina.nome,
          tipo: editingMacchina.tipo,
          id_stabilimento: editingMacchina.id_stabilimento?.toString() || "",
          colore_testo: editingMacchina.colore_testo || "#3b82f6",
        });
      } else {
        setFormData({
          nome: "",
          tipo: parentId ? "gruppo" : "macchina",
          id_stabilimento: parentStabilimento?.toString() || "",
          colore_testo: "#3b82f6",
        });
      }
      setErrors({});
    }
  }, [isOpen, editingMacchina, parentId, parentStabilimento, isEditing]);

  const handleFieldChange = (field: keyof FormData, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.nome.trim()) {
      newErrors.nome = "Il nome è obbligatorio";
    }

    if (formData.tipo === "macchina" && !parentId && !formData.id_stabilimento) {
      newErrors.id_stabilimento = "Stabilimento obbligatorio per macchine di livello root";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async () => {
    if (!validateForm()) return;

    setIsSubmitting(true);
    try {
      await onConfirm({
        ...formData,
        id_padre: isEditing ? undefined : parentId,
      });
      onClose();
    } catch (error) {
      const message = error instanceof Error ? error.message : "Errore sconosciuto";
      setErrors({ submit: message });
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) return null;

  const getTitle = () => {
    const action = isEditing ? "Modifica" : "Nuova";
    const typeLabel = formData.tipo === "macchina" ? "Macchina" : formData.tipo === "gruppo" ? "Gruppo" : "Parte";
    return `${action} ${typeLabel}`;
  };

  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-md bg-zinc-900 rounded-xl border border-zinc-800 shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-zinc-800">
          <h3 className="text-lg font-semibold text-white">{getTitle()}</h3>
          <button
            onClick={onClose}
            disabled={isSubmitting}
            className="p-1 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>

        {/* Content */}
        <div className="px-5 py-4 space-y-4">
          {/* Nome */}
          <div>
            <label className="block text-sm font-medium text-zinc-300 mb-1.5">
              Nome <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              value={formData.nome}
              onChange={(e) => handleFieldChange("nome", e.target.value)}
              placeholder="Inserisci nome..."
              disabled={isSubmitting}
              className={`w-full px-3 py-2 text-sm rounded-lg bg-zinc-800 border text-white placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-blue-500/50
                ${errors.nome ? "border-red-500" : "border-zinc-700"}`}
            />
            {errors.nome && <p className="mt-1 text-xs text-red-400">{errors.nome}</p>}
          </div>

          {/* Tipo */}
          {!isEditing && (
            <div>
              <label className="block text-sm font-medium text-zinc-300 mb-1.5">Tipo</label>
              <select
                value={formData.tipo}
                onChange={(e) => handleFieldChange("tipo", e.target.value as TipoMacchina)}
                disabled={isSubmitting}
                className="w-full px-3 py-2 text-sm rounded-lg bg-zinc-800 border border-zinc-700 text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50"
              >
                <option value="macchina">Macchina</option>
                <option value="gruppo">Gruppo</option>
                <option value="parte">Parte</option>
              </select>
            </div>
          )}

          {/* Stabilimento - solo per macchine root */}
          {formData.tipo === "macchina" && !parentId && (
            <div>
              <label className="block text-sm font-medium text-zinc-300 mb-1.5">
                Stabilimento <span className="text-red-400">*</span>
              </label>
              <select
                value={formData.id_stabilimento}
                onChange={(e) => handleFieldChange("id_stabilimento", e.target.value)}
                disabled={isSubmitting}
                className={`w-full px-3 py-2 text-sm rounded-lg bg-zinc-800 border text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50
                  ${errors.id_stabilimento ? "border-red-500" : "border-zinc-700"}`}
              >
                <option value="">Seleziona stabilimento...</option>
                {stabilimenti.map((s) => (
                  <option key={s.id} value={s.id}>{s.descrizione}</option>
                ))}
              </select>
              {errors.id_stabilimento && <p className="mt-1 text-xs text-red-400">{errors.id_stabilimento}</p>}
            </div>
          )}

          {/* Info ereditarietà stabilimento */}
          {parentId && parentStabilimento && (
            <div className="p-3 rounded-lg bg-blue-900/20 border border-blue-700/30">
              <p className="text-xs text-blue-300">
                Lo stabilimento verrà ereditato automaticamente dal padre.
              </p>
            </div>
          )}

          {/* Colore */}
          <div>
            <label className="block text-sm font-medium text-zinc-300 mb-1.5">Colore testo</label>
            <div className="flex items-center gap-3">
              <input
                type="color"
                value={formData.colore_testo}
                onChange={(e) => handleFieldChange("colore_testo", e.target.value)}
                disabled={isSubmitting}
                className="w-10 h-10 rounded-lg border border-zinc-700 cursor-pointer"
              />
              <input
                type="text"
                value={formData.colore_testo}
                onChange={(e) => handleFieldChange("colore_testo", e.target.value)}
                disabled={isSubmitting}
                className="flex-1 px-3 py-2 text-sm rounded-lg bg-zinc-800 border border-zinc-700 text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50"
              />
            </div>
          </div>

          {/* Error generale */}
          {errors.submit && (
            <div className="p-3 rounded-lg bg-red-900/20 border border-red-700/30">
              <p className="text-sm text-red-400">{errors.submit}</p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 px-5 py-4 border-t border-zinc-800">
          <button
            onClick={onClose}
            disabled={isSubmitting}
            className="px-4 py-2 text-sm font-medium text-zinc-300 hover:text-white rounded-lg hover:bg-zinc-800 transition-colors"
          >
            Annulla
          </button>
          <button
            onClick={handleSubmit}
            disabled={isSubmitting}
            className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            {isSubmitting && (
              <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>
            )}
            {isEditing ? "Aggiorna" : "Crea"}
          </button>
        </div>
      </div>
    </div>
  );
}
