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

import { useAuthContext } from '@/contexts/AuthContext'
import { UPDATE_USER_PROFILE, UPDATE_ORGANIZATION_BY_INN } from '@/graphql/mutations'
import { apolloClient } from '@/lib/apollo-client'

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

export function useOrganizationSettings() {
  const { user } = useAuthContext()
  const [,] = useMutation(UPDATE_USER_PROFILE)
  const [updateOrganizationByInn, { loading: isUpdatingOrganization }] = useMutation(UPDATE_ORGANIZATION_BY_INN)
  const [saveMessage, setSaveMessage] = useState<SaveMessage | null>(null)

  const initializeFormData = useCallback((): UserSettingsFormData => {
    if (!user?.organization) {
      return {
        orgPhone: '',
        managerName: '',
        telegram: '',
        whatsapp: '',
        email: '',
        orgName: '',
        address: '',
        fullName: '',
        inn: '',
        ogrn: '',
        registrationPlace: '',
        bankName: '',
        bik: '',
        accountNumber: '',
        corrAccount: '',
        wildberriesApiKey: '',
        ozonApiKey: '',
        market: '',
      }
    }

    const org = user.organization
    let orgPhone = ''
    if (org.phones && Array.isArray(org.phones) && org.phones.length > 0) {
      orgPhone = org.phones[0].value || org.phones[0] || ''
    }

    return {
      orgPhone,
      managerName: ((org as Record<string, unknown>).managerName as string) || '',
      telegram: ((org as Record<string, unknown>).telegram as string) || '',
      whatsapp: ((org as Record<string, unknown>).whatsapp as string) || '',
      email: ((org as Record<string, unknown>).email as string) || '',
      orgName: org.name || ((org as Record<string, unknown>).orgName as string) || '',
      address: org.address || '',
      fullName: org.fullName || '',
      inn: org.inn || '',
      ogrn: org.ogrn || '',
      registrationPlace: ((org as Record<string, unknown>).registrationPlace as string) || '',
      bankName: ((org as Record<string, unknown>).bankName as string) || '',
      bik: ((org as Record<string, unknown>).bik as string) || '',
      accountNumber: ((org as Record<string, unknown>).accountNumber as string) || '',
      corrAccount: ((org as Record<string, unknown>).corrAccount as string) || '',
      wildberriesApiKey: ((org as Record<string, unknown>).wildberriesApiKey as string) || '',
      ozonApiKey: ((org as Record<string, unknown>).ozonApiKey as string) || '',
      market: ((org as Record<string, unknown>).market as string) || '',
    }
  }, [user])

  const searchDaData = useCallback(async (inn: string) => {
    if (!inn || inn.length < 10) return

    try {
      const response = await fetch(`/api/dadata/suggest/party?query=${inn}`)
      const data = await response.json()

      if (data.suggestions && data.suggestions.length > 0) {
        const suggestion = data.suggestions[0]
        return {
          orgName: suggestion.value || '',
          fullName: suggestion.data?.name?.full_with_opf || '',
          address: suggestion.data?.address?.value || '',
          inn: suggestion.data?.inn || '',
          ogrn: suggestion.data?.ogrn || '',
          registrationPlace: suggestion.data?.address?.value || '',
        }
      }
    } catch (error) {
      console.error('Ошибка поиска в DaData:', error)
      setSaveMessage({ type: 'error', text: 'Ошибка при поиске данных организации' })
    }
    return null
  }, [])

  const saveOrganizationData = useCallback(
    async (formData: UserSettingsFormData) => {
      if (!user?.organization?.id) return false

      try {
        await updateOrganizationByInn({
          variables: {
            id: user.organization.id,
            input: {
              orgName: formData.orgName,
              address: formData.address,
              fullName: formData.fullName,
              inn: formData.inn,
              ogrn: formData.ogrn,
              registrationPlace: formData.registrationPlace,
              bankName: formData.bankName,
              bik: formData.bik,
              accountNumber: formData.accountNumber,
              corrAccount: formData.corrAccount,
              managerName: formData.managerName,
              telegram: formData.telegram,
              whatsapp: formData.whatsapp,
              email: formData.email,
              wildberriesApiKey: formData.wildberriesApiKey,
              ozonApiKey: formData.ozonApiKey,
              market: formData.market,
              phones: formData.orgPhone ? [{ value: formData.orgPhone }] : [],
            },
          },
        })

        await apolloClient.refetchQueries({ include: ['GetMe'] })
        setSaveMessage({ type: 'success', text: 'Данные организации успешно сохранены' })
        return true
      } catch (error) {
        console.error('Ошибка сохранения данных организации:', error)
        setSaveMessage({ type: 'error', text: 'Ошибка при сохранении данных организации' })
        return false
      }
    },
    [user, updateOrganizationByInn],
  )

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

  return {
    initializeFormData,
    searchDaData,
    saveOrganizationData,
    isUpdatingOrganization,
    saveMessage,
    clearSaveMessage,
  }
}
