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

export type User = {
    id: number;
    username: string;
    email: string;
    has_password: boolean;
    google_id?: string | null;
    avatar?: string;
    banner_file?: string;
    description?: string;
    premium?: boolean;
    is_banned?: boolean;
    is_moderator?: boolean;
    token_version?: number;
    profile?: {
        id: number;
        user_id: number;
        avatar_file?: string;
        banner_file?: string;
        description?: string;
        publications_count?: number;
        collections_count?: number;
        subscriptions_count?: number;
        followers_count?: number;
        following_count?: number;
    };
    integrations?: {
        facebook?: string | null;
        pinterest?: string | null;
        discord?: string | null;
        artstation?: string | null;
        x?: string | null; // Twitter/X
        behance?: string | null;
        instagram?: string | null;
    };
};

interface AuthContextType {
    user: User | null;
    setUser: (user: User | null) => void;
    logout: () => void;
}
const AuthContext = createContext<AuthContextType | null>(null);
const API_URL = process.env.NEXT_PUBLIC_API_URL;

export const AuthContextProvider = ({ children }: React.PropsWithChildren) => {
    const [user, setUser] = useState<User | null>(null);

    useEffect(() => {
        const fetchUser = async () => {
            try {
                const res = await fetch(`${API_URL}/api/me`, {
                    credentials: 'include',
                });
                if (!res.ok) {
                    setUser(null);
                    return;
                }
                const data = await res.json();
                setUser(data.authenticated ? data.user : null);
            } catch (err) {
                console.error('Error fetching user:', err);
                setUser(null);
            }
        };

        fetchUser();
    }, []);

    const logout = async () => {
        await fetch(`${API_URL}/api/auth/logout`, {
            method: 'POST',
            credentials: 'include',
        });
        setUser(null);
    };

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

export const useAuthContext = () => {
    const context = useContext(AuthContext);
    if (!context)
        throw new Error(
            'useAuthContext must be used within AuthContextProvider',
        );
    return context;
};

export const useUser = () => useAuthContext().user;
export const useLogout = () => useAuthContext().logout;
