import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  useCallback,
} from "react";
import { 
  pb, 
  signIn, 
  signUp, 
  signOut, 
  getCurrentUser 
} from '../services/pocketbaseService';
import { useCache } from '../hooks/useCache';
import { useErrorBoundary } from '../hooks/useErrorBoundary';

const AuthContext = createContext(null);

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

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [userProfile, setUserProfile] = useState(null);
  const [loading, setLoading] = useState(true);
  const [isInitialized, setIsInitialized] = useState(false);
  const { error, handleError, clearError } = useErrorBoundary();

  // Кэширование профиля пользователя
  const { data: cachedProfile, refetch: refetchProfile } = useCache(
    user ? `profile_${user.id}` : null,
    async () => {
      if (!user) return null;
      try {
        const profile = await pb.collection('users').getOne(user.id);
        return profile;
      } catch (err) {
        console.error('Error fetching profile:', err);
        handleError(err);
        return null;
      }
    },
    {
      expiry: 5 * 60 * 1000, // 5 минут
      dependencies: [user?.id]
    }
  );

  // Инициализация аутентификации
  useEffect(() => {
    let mounted = true;

    const initializeAuth = async () => {
      if (!mounted) return;

      try {
        setLoading(true);
        const currentUser = getCurrentUser();
        
        if (currentUser && mounted) {
          setUser(currentUser);
          try {
            const profile = await pb.collection('users').getOne(currentUser.id);
            if (mounted) {
              setUserProfile(profile);
            }
          } catch (profileError) {
            console.error('Error fetching user profile:', profileError);
          }
        }
      } catch (error) {
        console.error('Ошибка инициализации:', error);
      } finally {
        if (mounted) {
          setLoading(false);
          setIsInitialized(true);
        }
      }
    };

    initializeAuth();

    // Подписываемся на изменения состояния аутентификации
    const unsubscribe = pb.authStore.onChange((token, model) => {
      if (!mounted) return;

      setUser(model);
      if (model) {
        pb.collection('users').getOne(model.id)
          .then(profile => {
            if (mounted) {
              setUserProfile(profile);
            }
          })
          .catch(error => console.error('Ошибка получения профиля:', error));
      } else {
        setUserProfile(null);
      }
    });

    return () => {
      mounted = false;
      unsubscribe();
    };
  }, []);

  // Обработчик входа
  const handleLogin = useCallback(async (username, password) => {
    try {
      clearError();
      console.log('Attempting login with:', { username, pbUrl: pb.baseUrl });
      const authData = await signIn(username, password);
      console.log('Login successful:', authData);
      setUser(authData);
      const profile = await pb.collection('users').getOne(authData.id);
      setUserProfile(profile);
      return profile;
    } catch (err) {
      console.error('Login error:', err);
      handleError(err);
      throw err;
    }
  }, [clearError, handleError]);

  // Обработчик выхода
  const handleLogout = useCallback(() => {
    try {
      clearError();
      signOut();
      setUser(null);
      setUserProfile(null);
    } catch (err) {
      handleError(err);
    }
  }, [clearError, handleError]);

  // Обработчик регистрации
  const handleRegister = useCallback(async (username, password, email = null) => {
    try {
      clearError();
      const result = await signUp(username, password, email);
      setUser(result.user);
      setUserProfile(result.profile);
      return result;
    } catch (err) {
      handleError(err);
      throw err;
    }
  }, [clearError, handleError]);

  const value = {
    user,
    userProfile: cachedProfile || userProfile,
    loading,
    isInitialized,
    error,
    login: handleLogin,
    logout: handleLogout,
    register: handleRegister,
    refetchProfile
  };

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