import React, { createContext, useContext, useState, ReactNode } from 'react';
import { getCookie, deleteCookie } from 'cookies-next';
import { useRouter } from 'next/router';

interface AuthContextType {
    token: string | null;
    setToken: (token: string | null) => void;
    logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
    const [token, setToken] = useState<string | null>(getCookie('authToken') || null);
    const router = useRouter();

    const logout = () => {
        setToken(null);
        deleteCookie('authToken');
        router.push('/login');
    };

    return (
        <AuthContext.Provider value={{ token, setToken, logout }}>
            {children}
        </AuthContext.Provider>
    );
};

export const useAuthCustomer = () => {
    const context = useContext(AuthContext);
    if (!context) {
        throw new Error('useAuth must be used within an AuthProvider');
    }
    return context;
};