"use client";

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

interface Selection {
  stabilimento: Stabilimento | null;
  magazzino: Magazzino | null;
}

interface StabilimentoMagazzinoSelectorProps {
  onSelectionChange: (selection: Selection) => void;
}

export default function StabilimentoMagazzinoSelector({
  onSelectionChange,
}: StabilimentoMagazzinoSelectorProps) {
  const [stabilimenti, setStabilimenti] = useState<Stabilimento[]>([]);
  const [magazzini, setMagazzini] = useState<Magazzino[]>([]);
  const [selectedStabilimento, setSelectedStabilimento] = useState<Stabilimento | null>(null);
  const [selectedMagazzino, setSelectedMagazzino] = useState<Magazzino | null>(null);
  const [loading, setLoading] = useState(true);

  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);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, []);

  const handleStabilimentoSelect = (stab: Stabilimento | null) => {
    setSelectedStabilimento(stab);
    setSelectedMagazzino(null);
    onSelectionChange({ stabilimento: stab, magazzino: null });
  };

  const handleMagazzinoSelect = (mag: Magazzino | null) => {
    setSelectedMagazzino(mag);
    onSelectionChange({ stabilimento: selectedStabilimento, magazzino: mag });
  };

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

  if (loading) {
    return (
      <div className="flex items-center gap-2 text-zinc-500 text-sm">
        <svg className="animate-spin h-4 w-4" 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>
        Caricamento...
      </div>
    );
  }

  return (
    <div className="flex flex-wrap items-center gap-4">
      {/* Stabilimenti */}
      <div className="flex items-center gap-2">
        <span className="text-xs text-zinc-500 uppercase tracking-wider">Stabilimento:</span>
        <div className="flex gap-1">
          {stabilimenti.map((stab) => (
            <button
              key={stab.id}
              onClick={() => handleStabilimentoSelect(
                selectedStabilimento?.id === stab.id ? null : stab
              )}
              className={`
                px-3 py-1.5 text-sm rounded-lg font-medium transition-all
                ${selectedStabilimento?.id === stab.id
                  ? "bg-blue-600 text-white"
                  : "bg-zinc-800 text-zinc-400 hover:bg-zinc-700 hover:text-white"
                }
              `}
            >
              {stab.descrizione}
            </button>
          ))}
        </div>
      </div>

      {/* Magazzini (visibile solo se stabilimento selezionato) */}
      {selectedStabilimento && filteredMagazzini.length > 0 && (
        <div className="flex items-center gap-2">
          <span className="text-xs text-zinc-500 uppercase tracking-wider">Magazzino:</span>
          <div className="flex gap-1">
            <button
              onClick={() => handleMagazzinoSelect(null)}
              className={`
                px-3 py-1.5 text-sm rounded-lg font-medium transition-all
                ${!selectedMagazzino
                  ? "bg-green-600 text-white"
                  : "bg-zinc-800 text-zinc-400 hover:bg-zinc-700 hover:text-white"
                }
              `}
            >
              Tutti
            </button>
            {filteredMagazzini.map((mag) => (
              <button
                key={mag.id}
                onClick={() => handleMagazzinoSelect(
                  selectedMagazzino?.id === mag.id ? null : mag
                )}
                className={`
                  px-3 py-1.5 text-sm rounded-lg font-medium transition-all
                  ${selectedMagazzino?.id === mag.id
                    ? "bg-green-600 text-white"
                    : "bg-zinc-800 text-zinc-400 hover:bg-zinc-700 hover:text-white"
                  }
                `}
              >
                {mag.descrizione}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Info selezione */}
      {selectedStabilimento && (
        <div className="flex items-center gap-2 ml-auto">
          <span className="text-xs text-zinc-600">
            {selectedMagazzino 
              ? `Filtro: ${selectedMagazzino.descrizione}`
              : `Tutti i magazzini di ${selectedStabilimento.descrizione}`
            }
          </span>
          <button
            onClick={() => handleStabilimentoSelect(null)}
            className="p-1 text-zinc-500 hover:text-white transition-colors"
            title="Reset selezione"
          >
            <svg className="w-4 h-4" 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>
      )}
    </div>
  );
}
