import { useEffect, useState } from 'react'
import { useUpdatePhone } from '@features/auth'

type PhoneNotification = { message: string; status: 'success' | 'error' }

// Owns the editable phone field: local value synced from the server, input
// sanitization, save-on-blur, and the resulting success/error notification.
// The notification has no meaning outside this flow, so it lives here too.
export function usePhoneField(serverPhone: string | null) {
  const updatePhone = useUpdatePhone()
  const [phone, setPhone] = useState('')
  const [savedPhone, setSavedPhone] = useState('')
  const [notification, setNotification] = useState<PhoneNotification | null>(null)

  useEffect(() => {
    if (serverPhone != null) {
      setPhone(serverPhone)
      setSavedPhone(serverPhone)
    }
  }, [serverPhone])

  function onPhoneChange(value: string) {
    setPhone(value.replace(/[^\d+\s()-]/g, ''))
  }

  function onPhoneBlur() {
    const next = phone.trim()
    if (next === savedPhone || updatePhone.isPending) return
    updatePhone.mutate(next, {
      onSuccess: () => {
        setSavedPhone(next)
        setNotification({ status: 'success', message: 'Номер телефона обновлён' })
      },
      onError: () => {
        setNotification({ status: 'error', message: 'Не удалось обновить номер телефона' })
      },
    })
  }

  return {
    phone,
    onPhoneChange,
    onPhoneBlur,
    notification,
    dismissNotification: () => setNotification(null),
  }
}
