'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import type { DeletedCharacter } from '@/lib/restore-character'

function restoreError(t: ReturnType<typeof useTranslations>, error?: string): string {
  switch (error) {
    case 'notFound':
      return t('restoreChar.errors.notFound')
    case 'notDeleted':
      return t('restoreChar.errors.notDeleted')
    case 'levelTooLow':
      return t('restoreChar.errors.levelTooLow')
    case 'tooOld':
      return t('restoreChar.errors.tooOld')
    case 'dkExists':
      return t('restoreChar.errors.dkExists')
    case 'nameTaken':
      return t('restoreChar.errors.nameTaken')
    case 'cooldown':
      return t('restoreChar.errors.cooldown')
    case 'notAuthenticated':
      return t('restoreChar.errors.notAuthenticated')
    default:
      return t('restoreChar.errors.default')
  }
}

export function RestoreCharacterForm({ characters }: { characters: DeletedCharacter[] }) {
  const t = useTranslations('CharService')
  const router = useRouter()
  const [guid, setGuid] = useState('')
  const [busy, setBusy] = useState(false)
  const [done, setDone] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  const selectedCss = characters.find((c) => String(c.guid) === guid)?.classCss

  if (characters.length === 0) {
    return (
      <div className="centered">
        <br />
        <br />
        <span>{t('restoreChar.noCharacters')}</span>
        <br />
      </div>
    )
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (busy || done || !guid) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/character/restore', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ guid: Number(guid) }),
      })
      const data: { success?: boolean; error?: string; name?: string } = await res.json()
      if (data.success) {
        setDone(true)
        setMessage({ ok: true, text: t('restoreChar.successMsg', { name: data.name ?? '' }) })
        setTimeout(() => router.refresh(), 3000)
      } else {
        setMessage({ ok: false, text: restoreError(t, data.error) })
      }
    } catch {
      setMessage({ ok: false, text: restoreError(t) })
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="centered">
      <form noValidate id="ns-restore-form" onSubmit={handleSubmit} acceptCharset="utf-8">
        <select className={selectedCss} value={guid} onChange={(e) => setGuid(e.target.value)} required>
          <option value="" disabled>{t('restoreChar.selectPlaceholder')}</option>
          {characters.map((c) => (
            <option key={c.guid} value={c.guid} className={`${c.classCss} big-font`}>
              {t('restoreChar.optionLabel', { name: c.name, level: c.level })}
            </option>
          ))}
        </select>
        <br />
        <button type="submit" className="restore-button" disabled={busy || done || !guid} style={done ? { color: '#d79602' } : undefined}>
          {done ? t('restoreChar.restored') : busy ? t('restoreChar.recovering') : t('restoreChar.recover')}
        </button>
      </form>
      <hr />
      <div className="alert-message" id="restore-response" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
    </div>
  )
}
