import { useState } from 'react'
import {
  loginAccount,
  registerAccount,
  type AuthSession,
} from '../actionApi'

type AuthScreenProps = {
  onAuthenticated: (session: AuthSession) => void
  onPlayOffline: () => void
  serverMessage?: string
}

export function AuthScreen({ onAuthenticated, onPlayOffline, serverMessage = '' }: AuthScreenProps) {
  const [mode, setMode] = useState<'login' | 'register'>('login')
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [characterName, setCharacterName] = useState('')
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState('')

  async function submit(event: React.FormEvent) {
    event.preventDefault()
    setBusy(true)
    setMessage('')
    try {
      const session = mode === 'login'
        ? await loginAccount(username, password)
        : await registerAccount(username, password, characterName)
      onAuthenticated(session)
    } catch (reason) {
      setMessage(reason instanceof Error ? reason.message : 'Unable to authenticate.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <main className="auth-shell">
      <section className="auth-panel">
        <div className="auth-brand">
          <p className="eyebrow">Action Healer</p>
          <h1>I Want To Heal 2</h1>
          <p>
            Sign in to sync saves to the server, keep progression across devices,
            and queue for PvP matchmaking.
          </p>
        </div>

        <div className="auth-card">
          <div className="auth-tabs">
            <button
              className={mode === 'login' ? 'selected' : ''}
              onClick={() => {
                setMode('login')
                setMessage('')
              }}
              type="button"
            >
              Sign In
            </button>
            <button
              className={mode === 'register' ? 'selected' : ''}
              onClick={() => {
                setMode('register')
                setMessage('')
              }}
              type="button"
            >
              Create
            </button>
          </div>

          <form onSubmit={submit}>
            <label>
              Username
              <input
                autoComplete="username"
                maxLength={20}
                minLength={3}
                onChange={(event) => setUsername(event.target.value)}
                pattern="[A-Za-z0-9_]+"
                required
                value={username}
              />
            </label>
            {mode === 'register' && (
              <label>
                Character Name
                <input
                  autoComplete="nickname"
                  maxLength={20}
                  minLength={2}
                  onChange={(event) => setCharacterName(event.target.value)}
                  required
                  value={characterName}
                />
              </label>
            )}
            <label>
              Password
              <input
                autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
                maxLength={128}
                minLength={10}
                onChange={(event) => setPassword(event.target.value)}
                required
                type="password"
                value={password}
              />
            </label>
            <button className="primary-button" disabled={busy} type="submit">
              {busy
                ? 'Working...'
                : mode === 'login'
                  ? 'Enter'
                  : 'Create Account'}
            </button>
          </form>

          <button
            className="secondary-button auth-offline-button"
            disabled={busy}
            onClick={onPlayOffline}
            type="button"
          >
            Play Offline
          </button>

          <p className={`auth-message ${message ? 'error' : ''}`}>
            {message || serverMessage || (
              mode === 'register'
                ? 'Creates an account and uploads the current local save if one exists.'
                : 'Sign in to load your server save.'
            )}
          </p>
        </div>
      </section>
    </main>
  )
}
