'use client'

import { useField } from '@payloadcms/ui'
import { useLayoutEffect, useRef } from 'react'

function formatEuros(cents: number | null | undefined): string {
  if (cents == null) return ''
  const euros = cents / 100
  return euros.toLocaleString('fr-FR', { maximumFractionDigits: 2 })
}

function parseEuros(text: string): number | null {
  const cleaned = text.replace(/[^\d,.\s-]/g, '').replace(/\s/g, '').replace(',', '.')
  if (!cleaned) return null
  const n = Number(cleaned)
  if (!Number.isFinite(n)) return null
  return Math.round(n * 100)
}

export function PriceEditable() {
  const { value, setValue } = useField<number | null>({ path: 'price' })
  const { value: currency } = useField<string>({ path: 'currency' })
  const ref = useRef<HTMLSpanElement | null>(null)

  useLayoutEffect(() => {
    const el = ref.current
    if (!el) return
    if (typeof document !== 'undefined' && document.activeElement === el) return
    const rendered = formatEuros(value)
    if (el.textContent !== rendered) el.textContent = rendered
    el.classList.toggle('rebours-editable--empty', value == null)
  }, [value])

  const commit = (e: React.FocusEvent<HTMLSpanElement>) => {
    const txt = e.currentTarget.textContent ?? ''
    const cents = parseEuros(txt)
    if (cents !== value) setValue(cents)
    e.currentTarget.textContent = formatEuros(cents)
    e.currentTarget.classList.toggle('rebours-editable--empty', cents == null)
  }

  const onKeyDown = (e: React.KeyboardEvent<HTMLSpanElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      ;(e.currentTarget as HTMLElement).blur()
    }
  }

  const symbol = currency === 'USD' ? '$' : '€'

  return (
    <span className="checkout-price">
      <span
        ref={ref}
        className="rebours-editable"
        contentEditable
        suppressContentEditableWarning
        spellCheck={false}
        onBlur={commit}
        onKeyDown={onKeyDown}
        data-placeholder="—"
      />{' '}
      {symbol}
    </span>
  )
}
