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 } = useMockStore();

    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) {
                setUser(foundUser);
                setIsAuthenticated(true);
                logger.info("User logged in successfully", { userId: foundUser.id, role: foundUser.role });
                toast.success(`Welcome back, ${foundUser.name}!`);
                return { success: true, role: foundUser.role || 'CUSTOMER' };
            }

            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);
        }
    };

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

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