'use client';

/**
 * Authentication Context
 * Provides authentication state and methods throughout the app
 */

import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { authAPI } from '@/lib/api/auth';

const AuthContext = createContext(undefined);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // Initialize auth state from localStorage
  useEffect(() => {
    const initAuth = () => {
      if (typeof window !== 'undefined') {
        const storedToken = localStorage.getItem('token');
        const storedUser = localStorage.getItem('user');

        if (storedToken && storedUser) {
          try {
            setToken(storedToken);
            setUser(JSON.parse(storedUser));
            setIsAuthenticated(true);
          } catch (error) {
            console.error('Error parsing stored user:', error);
            localStorage.removeItem('token');
            localStorage.removeItem('user');
          }
        }
      }
      setIsLoading(false);
    };

    initAuth();
  }, []);

  /**
   * Login function
   */
  const login = useCallback(async (username, password) => {
    try {
      const response = await authAPI.login(username, password);
      
      if (response.success && response.data) {
        const { token: authToken, user: userData } = response.data;
        
        // Store token and user
        if (typeof window !== 'undefined') {
          localStorage.setItem('token', authToken);
          localStorage.setItem('user', JSON.stringify(userData));
        }
        
        setToken(authToken);
        setUser(userData);
        setIsAuthenticated(true);
        
        return { success: true, user: userData };
      }
      
      throw new Error(response.message || 'Login failed');
    } catch (error) {
      return {
        success: false,
        error: error.message || 'Login failed',
      };
    }
  }, []);

  /**
   * Login with PIN
   */
  const loginWithPin = useCallback(async (username, pinCode) => {
    try {
      const response = await authAPI.loginWithPin(username, pinCode);
      
      if (response.success && response.data) {
        const { token: authToken, user: userData } = response.data;
        
        if (typeof window !== 'undefined') {
          localStorage.setItem('token', authToken);
          localStorage.setItem('user', JSON.stringify(userData));
        }
        
        setToken(authToken);
        setUser(userData);
        setIsAuthenticated(true);
        
        return { success: true, user: userData };
      }
      
      throw new Error(response.message || 'Login failed');
    } catch (error) {
      return {
        success: false,
        error: error.message || 'Login failed',
      };
    }
  }, []);

  /**
   * Logout function
   */
  const logout = useCallback(() => {
    authAPI.logout();
    setToken(null);
    setUser(null);
    setIsAuthenticated(false);
  }, []);

  /**
   * Check if user has specific role
   */
  const hasRole = useCallback((role) => {
    if (!user) return false;
    return user.role === role;
  }, [user]);

  /**
   * Check if user has any of the specified roles
   */
  const hasAnyRole = useCallback((roles) => {
    if (!user) return false;
    return roles.includes(user.role);
  }, [user]);

  const value = {
    user,
    token,
    isLoading,
    isAuthenticated,
    login,
    loginWithPin,
    logout,
    hasRole,
    hasAnyRole,
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

/**
 * Hook to use auth context
 */
export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}

