"use client";

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

interface StabilimentoContextValue {
  stabilimenti: Stabilimento[];
  magazzini: Magazzino[];
  selectedStabilimento: Stabilimento | null;
  selectedMagazzino: Magazzino | null;
  loading: boolean;
  setSelectedStabilimento: (stabilimento: Stabilimento | null) => void;
  setSelectedMagazzino: (magazzino: Magazzino | null) => void;
  filteredMagazzini: Magazzino[];
  resetSelection: () => void;
}

const StabilimentoContext = createContext<StabilimentoContextValue | null>(null);

export function StabilimentoProvider({ children }: { children: ReactNode }) {
  const [stabilimenti, setStabilimenti] = useState<Stabilimento[]>([]);
  const [magazzini, setMagazzini] = useState<Magazzino[]>([]);
  const [selectedStabilimento, setSelectedStabilimentoState] = useState<Stabilimento | null>(null);
  const [selectedMagazzino, setSelectedMagazzinoState] = 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) {
          const stabData = await stabRes.json();
          setStabilimenti(stabData.stabilimenti || []);
        }

        if (magRes.ok) {
          const magData = await magRes.json();
          setMagazzini(magData.magazzini || []);
        }
      } catch (error) {
        console.error("Errore caricamento stabilimenti/magazzini:", error);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, []);

  const setSelectedStabilimento = useCallback((stabilimento: Stabilimento | null) => {
    setSelectedStabilimentoState(stabilimento);
    setSelectedMagazzinoState(null);
  }, []);

  const setSelectedMagazzino = useCallback((magazzino: Magazzino | null) => {
    setSelectedMagazzinoState(magazzino);
  }, []);

  const resetSelection = useCallback(() => {
    setSelectedStabilimentoState(null);
    setSelectedMagazzinoState(null);
  }, []);

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

  return (
    <StabilimentoContext.Provider
      value={{
        stabilimenti,
        magazzini,
        selectedStabilimento,
        selectedMagazzino,
        loading,
        setSelectedStabilimento,
        setSelectedMagazzino,
        filteredMagazzini,
        resetSelection,
      }}
    >
      {children}
    </StabilimentoContext.Provider>
  );
}

export function useStabilimento() {
  const context = useContext(StabilimentoContext);
  
  if (!context) {
    throw new Error("useStabilimento deve essere usato dentro StabilimentoProvider");
  }
  
  return context;
}
