import { useState, useEffect, createContext, useContext, ReactNode } from 'react';
import { authAPI } from '../services/api';
import Cookies from 'js-cookie';

interface User {
    id: string;
    email: string;
    name: string;
    role: string;
    isEmailVerified: boolean;
}

interface AuthContextType {
    user: User | null;
    loading: boolean;
    login: (email: string, password: string) => Promise<void>;
    register: (email: string, password: string, name: string) => Promise<{ licenseKey: string }>;
    logout: () => void;
    isAdmin: boolean;
    isPro: boolean;
}

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

export function AuthProvider({ children }: { children: ReactNode }) {
    const [user, setUser] = useState<User | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        checkAuth();
    }, []);

    const checkAuth = async () => {
        const token = Cookies.get('accessToken');
        if (!token) {
            setLoading(false);
            return;
        }
        try {
            const { data } = await authAPI.me();
            setUser(data.data);
        } catch {
            Cookies.remove('accessToken');
            Cookies.remove('refreshToken');
        }
        setLoading(false);
    };

    const login = async (email: string, password: string) => {
        const { data } = await authAPI.login({ email, password });
        const { user: userData, tokens } = data.data;
        Cookies.set('accessToken', tokens.accessToken, { expires: 1 });
        Cookies.set('refreshToken', tokens.refreshToken, { expires: 7 });
        setUser(userData);
    };

    const register = async (email: string, password: string, name: string) => {
        const { data } = await authAPI.register({ email, password, name });
        const { user: userData, tokens, licenseKey } = data.data;
        Cookies.set('accessToken', tokens.accessToken, { expires: 1 });
        Cookies.set('refreshToken', tokens.refreshToken, { expires: 7 });
        setUser(userData);
        return { licenseKey };
    };

    const logout = () => {
        authAPI.logout().catch(() => { });
        Cookies.remove('accessToken');
        Cookies.remove('refreshToken');
        setUser(null);
    };

    return (
        <AuthContext.Provider
            value={{
                user,
                loading,
                login,
                register,
                logout,
                isAdmin: user?.role === 'ADMIN',
                isPro: user?.role === 'USER_PRO' || user?.role === 'ADMIN',
            }}
        >
            {children}
        </AuthContext.Provider>
    );
}

export function useAuth() {
    const ctx = useContext(AuthContext);
    if (!ctx) throw new Error('useAuth must be used within AuthProvider');
    return ctx;
}
