'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'

function promoErrorKey(error?: string): string {
  switch (error) {
    case 'missingCode':
    case 'notFound':
    case 'expired':
    case 'exhausted':
    case 'alreadyUsed':
    case 'notAuthenticated':
      return error
    default:
      return 'generic'
  }
}

export function PromoCodeForm() {
  const t = useTranslations('Points')
  const promoError = (error?: string) => t(`promo.errors.${promoErrorKey(error)}`)
  const router = useRouter()
  const [code, setCode] = useState('')
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (busy || !code.trim()) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/promo/redeem', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ code: code.trim() }),
      })
      const data: { success?: boolean; error?: string; pd?: number; pv?: number } = await res.json()
      if (data.success) {
        const parts: string[] = []
        if (data.pd) parts.push(t('promo.rewardPd', { pd: data.pd }))
        if (data.pv) parts.push(t('promo.rewardPv', { pv: data.pv }))
        const reward = parts.length ? parts.join(` ${t('promo.and')} `) : t('promo.rewardDefault')
        setMessage({ ok: true, text: t('promo.success', { reward }) })
        setCode('')
        router.refresh()
      } else {
        setMessage({ ok: false, text: promoError(data.error) })
      }
    } catch {
      setMessage({ ok: false, text: promoError() })
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="centered">
      <br />
      <form noValidate onSubmit={handleSubmit} acceptCharset="utf-8">
        <input
          type="text"
          maxLength={64}
          placeholder={t('promo.placeholder')}
          value={code}
          onChange={(e) => setCode(e.target.value)}
          required
        />
        <br />
        <button type="submit" className="dnt-button" disabled={busy || !code.trim()}>
          {busy ? t('promo.redeeming') : t('promo.redeemButton')}
        </button>
      </form>
      <hr />
      <div className="alert-message" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
    </div>
  )
}
