import React, { createContext, useState, useEffect } from 'react';

import userAPI from '../api/models/User';

// definice uživatele
export interface User {
  id: string;
  email: string;
  username: string;
}

// určíme typ kontextu
interface GlobalContextType {
  user: User | null;
  setUser: React.Dispatch<React.SetStateAction<User | null>>;
}

// vytvoříme a exportneme kontext !!!
export const UserContext = createContext<GlobalContextType | null>(null);


// hook pro použití kontextu
// zabal routy do téhle komponenty!!!
export const UserContextProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {

    const fetchUser = async () => {
      try {
        const currentUser = await userAPI.getCurrentUser();
        setUser(currentUser);
      } catch (error) {
        console.error('Failed to load user:', error);
        setUser(null);
      }
    };

    fetchUser();

  }, []);
    
  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
};


/*
EXAMPLE USAGE OF CONTEXT IN A COMPONENT:

// Wrap your app tree with the provider (e.g., in App.tsx)
// import { UserContextProvider } from "../context/UserContext";
// function App() {
//   return (
//     <UserContextProvider>
//       <YourRoutes />
//     </UserContextProvider>
//   );
// }

// Consume in any child component
import React, { useContext } from "react"
import { UserContext } from '../context/UserContext';

export default function ExampleComponent() {
  const { user, setUser } = useContext(UserContext);


  return ...;
}

*/