'use client'

import { useState } from 'react'
import { CharacterSelect, type CharOption } from '@/components/CharacterSelect'

/** Campo con ojo para mostrar/ocultar (contraseña / token). */
function SecretInput({
  id,
  value,
  onChange,
  placeholder,
  maxLength,
  toggleClass,
}: {
  id: string
  value: string
  onChange: (v: string) => void
  placeholder: string
  maxLength: number
  toggleClass: string
}) {
  const [show, setShow] = useState(false)
  return (
    <>
      <input
        type={show ? 'text' : 'password'}
        id={id}
        maxLength={maxLength}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        required
      />{' '}
      <span
        className={`far ${show ? 'fa-eye-slash' : 'fa-eye'} ${toggleClass}`}
        role="button"
        tabIndex={0}
        onClick={() => setShow((s) => !s)}
      />
    </>
  )
}

export function TransferForm({ characters, price }: { characters: CharOption[]; price: number }) {
  const [character, setCharacter] = useState('')
  const [destination, setDestination] = useState('')
  const [password, setPassword] = useState('')
  const [token, setToken] = useState('')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !character || !destination.trim() || !password || !token.trim()) return
    if (!window.confirm(`¿Estás seguro de transferir el personaje "${character}" a la cuenta ${destination.trim()} por ${price} € (SumUp)?`)) return
    setBusy(true)
    setError(null)
    try {
      const res = await fetch('/api/character/transfer/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({
          character,
          destination_account: destination.trim(),
          password,
          security_token: token.trim(),
          provider: 'sumup',
        }),
      })
      const data: { success?: boolean; url?: string; message?: string } = await res.json()
      if (data.success && data.url) window.location.href = data.url
      else {
        setError(data.message || 'No se pudo iniciar la transferencia. Inténtalo de nuevo.')
        setBusy(false)
      }
    } catch {
      setError('Algo ha salido mal. Inténtalo más tarde.')
      setBusy(false)
    }
  }

  if (characters.length === 0) return <p className="second-brown">No tienes personajes disponibles.</p>

  return (
    <div className="centered">
      <form id="uw-transfer-character-form" onSubmit={handleSubmit} acceptCharset="utf-8">
        <CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder="Selecciona un personaje" />
        <br />
        <input type="text" maxLength={32} placeholder="Cuenta de destino" value={destination} onChange={(e) => setDestination(e.target.value)} required />
        <br />
        <SecretInput id="password" value={password} onChange={setPassword} placeholder="Contraseña de tu cuenta" maxLength={16} toggleClass="toggle-password" />
        <br />
        <SecretInput id="security-token" value={token} onChange={setToken} placeholder="Token de seguridad" maxLength={6} toggleClass="toggle-token" />
        <br />
        <button type="submit" className="transfer-button" disabled={busy || !character || !destination.trim() || !password || !token.trim()}>
          {busy ? 'Transfiriendo personaje' : 'TRANSFERIR PERSONAJE'}
        </button>
      </form>
      <hr />
      <div className="alert-message" id="transfer-character-response" style={{ display: error ? 'block' : 'none' }}>
        {error && <span className="red-form-response">{error}</span>}
      </div>
    </div>
  )
}
