"use client";

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

interface StabilimentoSelectorProps {
  selectedId: number | null;
  onSelect: (stabilimento: Stabilimento | null) => void;
}

export default function StabilimentoSelector({
  selectedId,
  onSelect,
}: StabilimentoSelectorProps) {
  const [stabilimenti, setStabilimenti] = useState<Stabilimento[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchStabilimenti() {
      try {
        const res = await fetch("/api/stabilimenti");
        if (!res.ok) throw new Error("Errore nel caricamento");
        const data = await res.json();
        setStabilimenti(data.stabilimenti);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Errore sconosciuto");
      } finally {
        setLoading(false);
      }
    }

    fetchStabilimenti();
  }, []);

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

  if (error) {
    return (
      <div className="text-red-500 text-sm">
        {error}
      </div>
    );
  }

  return (
    <div className="flex flex-wrap gap-3">
      {stabilimenti.map((stab) => (
        <button
          key={stab.id}
          onClick={() => onSelect(selectedId === stab.id ? null : stab)}
          className={`
            px-4 py-2 rounded-lg font-medium transition-all duration-200
            ${
              selectedId === stab.id
                ? "bg-blue-600 text-white shadow-lg shadow-blue-600/30"
                : "bg-zinc-800 text-zinc-300 hover:bg-zinc-700 hover:text-white"
            }
          `}
        >
          {stab.descrizione}
        </button>
      ))}
    </div>
  );
}
