import { createContext, ReactNode, useContext, useEffect, useState } from "react";
import { AccountContextType, User } from "../components/Account";
import { useCookies } from 'react-cookie';

const AccountContext = createContext<AccountContextType | undefined>(undefined);

export const AccountProvider = ({ children }: { children: ReactNode }) => {
    const [cookies, setCookie] = useCookies(["account"]);

    const initialAccount =
    typeof cookies.account === "object" && !Array.isArray(cookies.account)
      ? cookies.account
      : null;
    const [user, setUser] = useState<User | null>(initialAccount);

    const login = (userData: User) => {
        setUser(userData);
    };

    const logout = () => {
        setUser(null);
    };

    useEffect(() => {
        setCookie("account", user, { path: "/", maxAge: 3600 * 24 * 7 });
      }, [user, setCookie]);

    return (
        <AccountContext.Provider value={{ user, login, logout }}>
            {children}
        </AccountContext.Provider>
    );
};

// eslint-disable-next-line react-refresh/only-export-components
export const useAccount = () => {
    const context = useContext(AccountContext);
    if (!context) {
        throw new Error("useAccount must be used within an AccountProvider");
    }
    return context;
};