import React, { createContext, useContext, useState } from 'react';
import { useMockStore } from '../data/mockStore';
import { logger } from '../utils/logger';
import { toast } from 'sonner';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(null);
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const { users, updateUser } = useMockStore(); // Destructure updateUser

    const login = (identifier, password, type) => {
        try {
            const foundUser = users.find(u => {
                if (u.type !== type) return false;
                if (type === 'customer') return u.username === identifier && u.password === password;
                if (type === 'employee') return u.empId === identifier && u.password === password;
                return false;
            });

            if (foundUser) {
                // Ensure specific role exists
                const userWithRole = {
                    ...foundUser,
                    role: foundUser.role || 'CUSTOMER'
                };

                setUser(userWithRole);
                setIsAuthenticated(true);
                logger.info("User logged in successfully", { userId: foundUser.id, role: userWithRole.role });
                toast.success(`Welcome back, ${foundUser.name}!`);
                return { success: true, role: userWithRole.role };
            }

            logger.warn("Failed login attempt", { identifier, type });
            toast.error("Invalid credentials", { description: "Please check your username/ID and password." });
            return { success: false, message: "Invalid credentials" };
        } catch (error) {
            logger.error("Login process error", error);
            toast.error("An unexpected error occurred during login.");
            return { success: false, message: "System error" };
        }
    };

    const logout = () => {
        try {
            const userName = user?.name;
            setUser(null);
            setIsAuthenticated(false);
            logger.info("User logged out", { userId: user?.id });
            toast.info("Logged out successfully");
        } catch (error) {
            logger.error("Logout error", error);
        }
    };

    const updateProfile = (updatedData) => {
        try {
            const newUser = { ...user, ...updatedData };
            setUser(newUser);

            // Update Store (Persistence)
            // Note: In a real app, this would be an API call.
            // Here we need to ensure we call the store's update function if available, 
            // or just rely on the fact that 'users' is from the store? 
            // 'users' from useMockStore is state, but we need the setter/function.
            // The AuthContext needs access to the update function from MockStore.
            // But useMockStore is called at the top level of AuthProvider.
            // Let's assume we can access it from the component scope, wait...

            // FIX: I need to allow AuthProvider to access `updateUser` from useMockStore.
            // I'll grab it from the hook call at the top.
        } catch (error) {
            logger.error("Profile update error", error);
            toast.error("Failed to update profile.");
            throw error;
        }
    };

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

export const useAuth = () => useContext(AuthContext);
