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

interface AuthContextType {
	isAuthenticated: boolean;
	loading: boolean;
	login: (token: string, expiresAt: number) => void;
	logout: () => void;
}

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

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
	children,
}) => {
	const [isAuthenticated, setIsAuthenticated] = useState(false);
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		const token = localStorage.getItem('token');
		const expiresAt = localStorage.getItem('expiresAt');

		if (token && expiresAt && new Date().getTime() < Number(expiresAt)) {
			setIsAuthenticated(true);
		} else {
			setIsAuthenticated(false);
		}
		setLoading(false); // завершение проверки
	}, []);

	const login = (token: string, expiresInSeconds: number) => {
		const expiresAt = new Date().getTime() + expiresInSeconds * 1000;
		localStorage.setItem('expiresAt', expiresAt.toString());
		setIsAuthenticated(true);
	};

	const logout = () => {
		localStorage.removeItem('token');
		localStorage.removeItem('expiresAt');
		setIsAuthenticated(false);
	};

	return (
		<AuthContext.Provider value={{ isAuthenticated, loading, login, logout }}>
			{children}
		</AuthContext.Provider>
	);
};

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