import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  useCallback,
} from "react";
import {
  pb, // Import PocketBase instance for authStore listener
  signUp as pbSignUp,
  signIn as pbSignIn,
  signOut as pbSignOut,
  getUserProfile,
  requestPasswordReset as pbRequestPasswordReset, // Import the new function
} from "../services/pocketbaseService"; // Use the new service file
import { getNotificationSettings } from '../services/notificationService';
import { useCache } from '../hooks/useCache';
import { useErrorBoundary } from '../hooks/useErrorBoundary';

const AuthContext = createContext(null);

export const useAuth = () => {
  // CORRECT: useContext is called at the top level of the useAuth hook function
  const context = useContext(AuthContext);
  if (!context) {
    // This error should ideally not happen if AuthProvider is used correctly
    // and handles its own initialization state before rendering children.
    console.error("useAuth must be used within an AuthProvider"); // Add error logging
    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) {
        handleError(err);
        return null;
      }
    },
    {
      expiry: 5 * 60 * 1000, // 5 минут
      dependencies: [user?.id]
    }
  );

  // Инициализация аутентификации
  useEffect(() => {
    const initializeAuth = async () => {
      try {
        setLoading(true);
        clearError();

        // Проверяем текущую сессию
        const authData = pb.authStore.model;
        if (authData) {
          setUser(authData);
          const profile = await pb.collection('users').getOne(authData.id);
          setUserProfile(profile);
        }
      } catch (err) {
        handleError(err);
      } finally {
        setLoading(false);
        setIsInitialized(true);
      }
    };

    initializeAuth();
  }, [clearError, handleError]);

  // Обработчик входа
  const login = useCallback(async (email, password) => {
    try {
      clearError();
      const authData = await pb.collection('users').authWithPassword(email, password);
      setUser(authData.record);
      const profile = await pb.collection('users').getOne(authData.record.id);
      setUserProfile(profile);
      return profile;
    } catch (err) {
      handleError(err);
      throw err;
    }
  }, [clearError, handleError]);

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

  // Обновление профиля
  const updateProfile = useCallback(async (data) => {
    try {
      clearError();
      if (!user) throw new Error('Пользователь не авторизован');
      
      const updatedProfile = await pb.collection('users').update(user.id, data);
      setUserProfile(updatedProfile);
      return updatedProfile;
    } catch (err) {
      handleError(err);
      throw err;
    }
  }, [user, clearError, handleError]);

  // Обработчик регистрации
  const signUp = useCallback(async (login, password, email = null) => {
    try {
      clearError();
      const result = await pbSignUp(login, 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,
    logout,
    signUp,
    updateProfile,
    refetchProfile
  };

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