import React, { createContext, useContext, useState, useEffect } from 'react';
import { User } from '../types';
import { authService } from '../services/authService';
import { useToast } from '@/components/feedback/ToastProvider';
import { logger } from '@/utils/logger';
import { parseApiError } from '@/utils/apiErrorHandler';

interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (credentials: any) => Promise<void>;
  register: (data: any) => Promise<void>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

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

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const { addToast } = useToast();

  useEffect(() => {
    checkAuth();
  }, []);

  const checkAuth = async () => {
    try {
      // SECURITY: Action 5.1.1.2 - Tokens are in httpOnly cookies, not localStorage
      // Just call getCurrentUser - if it works, user is authenticated
      const userData = await authService.getCurrentUser();
      setUser(userData);
    } catch (error) {
      logger.error('Auth check failed', {
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
      });
      // Tokens are in httpOnly cookies, cleared by backend on logout
      setUser(null);
    } finally {
      setIsLoading(false);
    }
  };

  const login = async (credentials: any) => {
    try {
      // SECURITY: Action 5.1.1.2 - Tokens are set in httpOnly cookies by backend
      const { user } = await authService.login(credentials);
      setUser(user);
      addToast('Welcome back!', 'success');
    } catch (error: unknown) {
      const apiError = parseApiError(error);
      addToast(apiError.message || 'Login failed', 'error');
      throw apiError;
    }
  };

  const register = async (data: any) => {
    try {
      // SECURITY: Action 5.1.1.2 - Tokens are set in httpOnly cookies by backend
      const { user } = await authService.register(data);
      setUser(user);
      addToast('Account created successfully', 'success');
    } catch (error: unknown) {
      const apiError = parseApiError(error);
      addToast(apiError.message || 'Registration failed', 'error');
      throw apiError;
    }
  };

  const logout = async () => {
    try {
      // SECURITY: Action 5.1.1.2 - Backend clears httpOnly cookies on logout
      await authService.logout();
    } catch (e) {
      logger.error('Logout error', {
        error: e instanceof Error ? e.message : String(e),
        stack: e instanceof Error ? e.stack : undefined,
      });
    }
    // Backend clears cookies, just clear local state
    setUser(null);
    addToast('Logged out', 'info');
  };

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