/**
 * Authentication Hook
 *
 * Provides auth context and methods for the app.
 */

import React, { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
import { loginApi, logoutApi, getProfile } from '../api/auth';
import {
  getAuthToken,
  setAuthToken,
  setUserData,
  getUserData,
  clearAllAuthData,
} from '../services/storage';
import type { User, LoginCredentials } from '../types';

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

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

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

  // Check for existing auth on mount
  useEffect(() => {
    checkAuthStatus();
  }, []);

  const checkAuthStatus = async () => {
    try {
      const token = await getAuthToken();
      if (token) {
        // Try to get cached user data first
        const cachedUser = await getUserData();
        if (cachedUser) {
          setUser(cachedUser);
        }
        // Then refresh from server
        try {
          const freshUser = await getProfile();
          setUser(freshUser);
          await setUserData(freshUser);
        } catch (error) {
          // If profile fetch fails, clear auth
          await clearAllAuthData();
          setUser(null);
        }
      }
    } catch (error) {
      console.error('Error checking auth status:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const login = useCallback(async (credentials: LoginCredentials) => {
    const response = await loginApi(credentials);
    await setAuthToken(response.access);
    await setUserData(response.user);
    setUser(response.user);
  }, []);

  const logout = useCallback(async () => {
    try {
      await logoutApi();
    } finally {
      await clearAllAuthData();
      setUser(null);
    }
  }, []);

  const refreshUser = useCallback(async () => {
    try {
      const freshUser = await getProfile();
      setUser(freshUser);
      await setUserData(freshUser);
    } catch (error) {
      console.error('Error refreshing user:', error);
    }
  }, []);

  const value: AuthContextType = {
    user,
    isAuthenticated: !!user,
    isLoading,
    login,
    logout,
    refreshUser,
  };

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

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