import { createContext, useContext, useEffect } from 'react';
import { useGetMe, getGetMeQueryKey, useUpdateLanguage } from '@workspace/api-client-react';
import type { AuthUser } from '@workspace/api-client-react';
import { useLocation } from 'wouter';
import { useQueryClient } from '@tanstack/react-query';
import i18n from '../i18n';

interface AuthContextType {
  user: AuthUser | null;
  isLoading: boolean;
}

const AuthContext = createContext<AuthContextType>({ user: null, isLoading: true });

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [location, setLocation] = useLocation();
  const queryClient = useQueryClient();

  const { data: user, isLoading, isError } = useGetMe({
    query: {
      queryKey: getGetMeQueryKey(),
      retry: false,
    }
  });

  const updateLanguage = useUpdateLanguage();

  useEffect(() => {
    if (!isLoading) {
      const publicRoutes = ['/login', '/register', '/forgot-password', '/reset-password'];
      const isPublic = publicRoutes.includes(location);
      if (isError || !user) {
        if (!isPublic) {
          setLocation('/login');
        }
      } else {
        if (user.preferredLanguage && user.preferredLanguage !== i18n.language) {
          i18n.changeLanguage(user.preferredLanguage);
        }
        if (location === '/login' || location === '/register') {
          setLocation('/');
        }
      }
    }
  }, [user, isLoading, isError, location, setLocation]);

  return (
    <AuthContext.Provider value={{ user: user || null, isLoading }}>
      {children}
    </AuthContext.Provider>
  );
}

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