"use client";

import { createContext, useContext, useState, useEffect, ReactNode } from "react";

interface Site {
  id: string;
  name: string;
}

interface SiteContextType {
  sites: Site[];
  selectedSiteId: string | null;
  selectedSite: Site | null;
  setSelectedSiteId: (siteId: string | null) => void;
  isLoading: boolean;
}

const SiteContext = createContext<SiteContextType | undefined>(undefined);

export function SiteProvider({ children }: { children: ReactNode }) {
  const [sites, setSites] = useState<Site[]>([]);
  const [selectedSiteId, setSelectedSiteId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function fetchSites() {
      try {
        const response = await fetch("/api/sites");
        if (response.ok) {
          const data = await response.json();
          setSites(data.data || []);
        }
      } catch (error) {
        console.error("Failed to fetch sites:", error);
      } finally {
        setIsLoading(false);
      }
    }

    fetchSites();
  }, []);

  const selectedSite = sites.find((site) => site.id === selectedSiteId) || null;

  return (
    <SiteContext.Provider
      value={{
        sites,
        selectedSiteId,
        selectedSite,
        setSelectedSiteId,
        isLoading,
      }}
    >
      {children}
    </SiteContext.Provider>
  );
}

export function useSite() {
  const context = useContext(SiteContext);
  if (context === undefined) {
    throw new Error("useSite must be used within a SiteProvider");
  }
  return context;
}
