"use client";

import {
  createContext,
  useContext,
  useState,
  useEffect,
  ReactNode,
} from "react";
import { authClient } from "@/clients";

interface UserInfo {
  firstName: string;
  lastName: string;
  teamName: string;
}

interface UserContextType {
  userInfo: UserInfo | null;
  setUserInfo: (userInfo: UserInfo | null) => void;
  loading: boolean;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export function UserProvider({ children }: { children: ReactNode }) {
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        // Récupérer les informations utilisateur depuis l'API
        const user = await authClient.getCurrentUser();
        if (user) {
          setUserInfo({
            firstName: user.firstName,
            lastName: user.lastName,
            teamName: user.teamName || "Équipe non définie",
          });
        }
      } catch (error) {
        console.error("Failed to fetch user info:", error);
        // En cas d'erreur, on considère que l'utilisateur n'est pas connecté
        setUserInfo(null);
      } finally {
        setLoading(false);
      }
    };

    fetchUserInfo();
  }, []);

  return (
    <UserContext.Provider value={{ userInfo, setUserInfo, loading }}>
      {children}
    </UserContext.Provider>
  );
}

export function useUser() {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error("useUser must be used within a UserProvider");
  }
  return context;
}
