import { useMutation } from '@apollo/client'
import { useState, useCallback } from 'react'

import { useAuthContext } from '@/contexts/AuthContext'
import { UPDATE_USER_PROFILE } from '@/graphql/mutations'
import S3Service from '@/services/s3-service'

import type { SaveMessage } from '../types/user-settings.types'

export function useProfileSettings() {
  const { user, updateUser } = useAuthContext()
  const [updateUserProfile, { loading: isSaving }] = useMutation(UPDATE_USER_PROFILE)
  const [isUploadingAvatar, setIsUploadingAvatar] = useState(false)
  const [localAvatarUrl, setLocalAvatarUrl] = useState<string | null>(null)
  const [saveMessage, setSaveMessage] = useState<SaveMessage | null>(null)

  const handleAvatarUpload = useCallback(
    async (file: File) => {
      if (!user?.id) return

      setIsUploadingAvatar(true)
      try {
        const avatarUrl = await S3Service.uploadAvatar(file, user.id)
        setLocalAvatarUrl(avatarUrl)

        await updateUserProfile({
          variables: {
            id: user.id,
            input: { avatar: avatarUrl },
          },
        })

        updateUser({ ...user, avatar: avatarUrl })
        setSaveMessage({ type: 'success', text: 'Аватар успешно обновлен' })
      } catch (error) {
        console.error('Ошибка загрузки аватара:', error)
        setSaveMessage({ type: 'error', text: 'Ошибка при загрузке аватара' })
      } finally {
        setIsUploadingAvatar(false)
      }
    },
    [user, updateUserProfile, updateUser],
  )

  const clearSaveMessage = useCallback(() => {
    setSaveMessage(null)
  }, [])

  return {
    user,
    localAvatarUrl,
    isUploadingAvatar,
    saveMessage,
    isSaving,
    handleAvatarUpload,
    clearSaveMessage,
  }
}
