import { useEffect, useState, type FormEvent } from 'react'
import {
  useCreatePurchaseRequest,
  useMyPurchaseRequests,
  TERM_OPTIONS,
  MIN_ORDER,
  formatRub,
  calcQuote,
  buildPurchaseComment,
  parseContactFromComment,
  latestPurchaseRequest,
} from '@features/b2b'

// Вся логика формы B2B-заявки: стейт полей, расчёт комиссии (через calcQuote),
// упаковка comment и отправка. По образцу widgets/converter-page/model.
export function useLegalConverterForm() {
  const [amount, setAmount] = useState('')
  const [name, setName] = useState('')
  const [contact, setContact] = useState('')
  const [days, setDays] = useState<number>(TERM_OPTIONS[0].days)
  const [notice, setNotice] = useState<'success' | 'error' | null>(null)

  const { mutate: submitRequest, isPending } = useCreatePurchaseRequest()
  const { data: requests } = useMyPurchaseRequests()

  // Автозаполнение имени и контакта из последней заявки аккаунта (один раз).
  const [prefilled, setPrefilled] = useState(false)
  useEffect(() => {
    if (prefilled || !requests) return
    const last = latestPurchaseRequest(requests.items)
    if (!last) return
    const parsed = parseContactFromComment(last.comment)
    if (parsed.name) setName(parsed.name)
    if (parsed.contact) setContact(parsed.contact)
    setPrefilled(true)
  }, [prefilled, requests])

  const numAmount = Number(amount.replace(/\D/g, '')) || 0
  const belowMin = numAmount > 0 && numAmount < MIN_ORDER

  const { rate, commission, total } = calcQuote(numAmount, days)

  const onAmountChange = (value: string) => {
    const digits = value.replace(/\D/g, '')
    setAmount(digits ? formatRub(Number(digits)) : '')
  }

  const canSubmit = numAmount > 0 && !belowMin && !isPending

  const onSubmit = (e: FormEvent) => {
    e.preventDefault()
    if (!canSubmit) return

    const comment = buildPurchaseComment({
      name,
      contact,
      days,
      amount: numAmount,
      commission,
      total,
    })

    submitRequest(
      { rub_amount: numAmount, comment },
      {
        onSuccess: () => {
          setNotice('success')
          setAmount('')
          setName('')
          setContact('')
          setDays(TERM_OPTIONS[0].days)
        },
        onError: () => setNotice('error'),
      },
    )
  }

  return {
    // значения полей
    amount,
    name,
    contact,
    days,
    // сеттеры
    setName,
    setContact,
    setDays,
    onAmountChange,
    // деривации для панели условий
    numAmount,
    belowMin,
    rate,
    commission,
    total,
    // отправка
    onSubmit,
    isPending,
    canSubmit,
    // нотификация
    notice,
    dismissNotice: () => setNotice(null),
  }
}
