'use client'

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

function renameErrorKey(error?: string): string {
  switch (error) {
    case 'missingFields':
    case 'invalidName':
    case 'invalidToken':
    case 'notGuildMaster':
    case 'nameTaken':
    case 'insufficientPoints':
    case 'soapError':
    case 'notAuthenticated':
      return error
    default:
      return 'generic'
  }
}

export function RenameGuildForm({ guilds }: { guilds: GmGuild[] }) {
  const t = useTranslations('Points')
  const renameError = (error?: string) => t(`renameGuild.errors.${renameErrorKey(error)}`)
  const router = useRouter()
  const [guildId, setGuildId] = useState('')
  const [newName, setNewName] = useState('')
  const [token, setToken] = useState('')
  const [showToken, setShowToken] = useState(false)
  const [busy, setBusy] = useState(false)
  const [done, setDone] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  if (guilds.length === 0) {
    return (
      <div className="centered">
        <br />
        <span>{t('renameGuild.noGuilds')}</span>
        <br />
      </div>
    )
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (busy || done) return
    if (!guildId || !newName.trim() || !token.trim()) {
      setMessage({ ok: false, text: renameError('missingFields') })
      return
    }
    if (!window.confirm(t('renameGuild.confirm'))) return

    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/guild/rename', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ guildId: Number(guildId), newName: newName.trim(), token: token.trim() }),
      })
      const data: { success?: boolean; error?: string; newName?: string } = await res.json()
      if (data.success) {
        setDone(true)
        setMessage({ ok: true, text: t('renameGuild.success', { newName: data.newName ?? '' }) })
        setNewName('')
        setToken('')
        setTimeout(() => router.refresh(), 3000)
      } else {
        setMessage({ ok: false, text: renameError(data.error) })
      }
    } catch {
      setMessage({ ok: false, text: renameError() })
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="centered">
      <form noValidate id="uw-rename-guild-form" onSubmit={handleSubmit} acceptCharset="utf-8">
        <table className="middle-center-table">
          <tbody>
            <tr>
              <td>
                <select value={guildId} onChange={(e) => setGuildId(e.target.value)} required>
                  <option value="" disabled>{t('renameGuild.selectGuild')}</option>
                  {guilds.map((g) => (
                    <option key={g.guildid} value={g.guildid}>{g.name}</option>
                  ))}
                </select>
              </td>
            </tr>
            <tr>
              <td>
                <input
                  type="text"
                  maxLength={24}
                  name="new-guild-name"
                  placeholder={t('renameGuild.newNamePlaceholder')}
                  value={newName}
                  onChange={(e) => setNewName(e.target.value)}
                  required
                />
              </td>
            </tr>
            <tr>
              <td>
                <input
                  type={showToken ? 'text' : 'password'}
                  maxLength={6}
                  id="security-token"
                  placeholder={t('renameGuild.tokenPlaceholder')}
                  value={token}
                  onChange={(e) => setToken(e.target.value)}
                  required
                />{' '}
                <span
                  className={`far ${showToken ? 'fa-eye-slash' : 'fa-eye'} toggle-token`}
                  role="button"
                  tabIndex={0}
                  onClick={() => setShowToken((s) => !s)}
                />
              </td>
            </tr>
            <tr>
              <td>
                <button type="submit" className="rename-guild-button" disabled={busy || done} style={done ? { color: '#d79602' } : undefined}>
                  {done ? t('renameGuild.renamed') : busy ? t('renameGuild.renaming') : t('renameGuild.renameButton')}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <div className="alert-message" id="rename-guild-response" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
    </div>
  )
}
