import { createContext, useState, useContext, useEffect } from 'react';
import api from '../api/api';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(null);
    const [activeRole, setActiveRole] = useState(null); // The role being "used" right now
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const storedUser = localStorage.getItem('user');
        const storedRole = localStorage.getItem('activeRole');
        if (storedUser) {
            const parsedUser = JSON.parse(storedUser);
            setUser(parsedUser);
            // Restore active role if stored, otherwise use user's primary role
            setActiveRole(storedRole || parsedUser.role);
        }
        setLoading(false);
    }, []);

    const login = async (email, password) => {
        try {
            const response = await api.post('/auth/login', { email, password });
            const userData = response.data;
            setUser(userData);
            localStorage.setItem('user', JSON.stringify(userData));
            return { success: true, user: userData };
        } catch (error) {
            return {
                success: false,
                message: error.response?.data?.message || 'Login failed'
            };
        }
    };

    const register = async (formData) => {
        try {
            const response = await api.post('/auth/register', formData);
            const data = response.data;
            setUser(data);
            // Default activeRole = first role selected
            const defaultRole = data.roles?.[0] || data.role;
            setActiveRole(defaultRole);
            localStorage.setItem('user', JSON.stringify(data));
            localStorage.setItem('activeRole', defaultRole);
            return { success: true };
        } catch (error) {
            return {
                success: false,
                message: error.response?.data?.message || 'Registration failed'
            };
        }
    };

    const logout = () => {
        setUser(null);
        setActiveRole(null);
        localStorage.removeItem('user');
        localStorage.removeItem('activeRole');
    };

    const updateProfile = (updatedData) => {
        const newUser = { ...user, ...updatedData };
        setUser(newUser);
        localStorage.setItem('user', JSON.stringify(newUser));
    };

    // Switch the "active role" the user is currently using (Customer <-> Photographer)
    const switchRole = (role) => {
        const availableRoles = user?.roles || [user?.role];
        if (!availableRoles.includes(role)) return;
        setActiveRole(role);
        localStorage.setItem('activeRole', role);
    };

    // Set active role after login (called by Login.jsx)
    const setLoginRole = (role) => {
        setActiveRole(role);
        localStorage.setItem('activeRole', role);
    };

    return (
        <AuthContext.Provider value={{ user, activeRole, login, register, logout, updateProfile, switchRole, setLoginRole, loading }}>
            {children}
        </AuthContext.Provider>
    );
};

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