import React, { createContext, useContext, useState, useCallback } from 'react';
import { pb } from '../services/pocketbaseService';
import { useErrorBoundary } from '../hooks/useErrorBoundary';

const ProfileActionsContext = createContext(null);

export const ProfileActionsProvider = ({ children }) => {
  const [loading, setLoading] = useState(false);
  const { error, handleError, clearError } = useErrorBoundary();

  // Обновление профиля
  const updateProfile = useCallback(async (userId, data) => {
    try {
      setLoading(true);
      clearError();
      const updatedProfile = await pb.collection('users').update(userId, data);
      return updatedProfile;
    } catch (err) {
      handleError(err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, [clearError, handleError]);

  // Обновление аватара
  const updateAvatar = useCallback(async (userId, file) => {
    try {
      setLoading(true);
      clearError();
      const formData = new FormData();
      formData.append('avatar', file);
      const updatedProfile = await pb.collection('users').update(userId, formData);
      return updatedProfile;
    } catch (err) {
      handleError(err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, [clearError, handleError]);

  // Обновление настроек уведомлений
  const updateNotificationSettings = useCallback(async (userId, settings) => {
    try {
      setLoading(true);
      clearError();
      const updatedSettings = await pb.collection('notification_settings').update(userId, settings);
      return updatedSettings;
    } catch (err) {
      handleError(err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, [clearError, handleError]);

  const value = {
    loading,
    error,
    updateProfile,
    updateAvatar,
    updateNotificationSettings
  };

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

export const useProfileActions = () => {
  const context = useContext(ProfileActionsContext);
  if (!context) {
    throw new Error('useProfileActions должен использоваться внутри ProfileActionsProvider');
  }
  return context;
};
