import { useEffect, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import { useGameStore } from '../store/gameStore';
import { emit } from '../lib/socket';
import { trackEvent } from '../lib/track';
import RulesModal from '../components/RulesModal';

type Mode = 'login' | 'register';

const inputCls =
  'bg-circle text-green-score rounded-lg px-4 py-2 border border-gold/20 outline-none focus:border-gold/60 focus:ring-1 focus:ring-gold/30 placeholder:text-green-dim/60';

export default function Auth() {
  const [mode, setMode] = useState<Mode>('login');
  const [username, setUsername] = useState(localStorage.getItem('bridzik_name') ?? '');
  const [code, setCode] = useState('');
  const [showRules, setShowRules] = useState(false);
  const registration = useGameStore((s) => s.registration);
  const setRegistration = useGameStore((s) => s.setRegistration);

  const remember = (name: string) => localStorage.setItem('bridzik_name', name.trim());

  // Server can push a registration payload even from the login tab (unfinished
  // registration → re-issued QR) — always land on the tab that shows it.
  useEffect(() => {
    if (registration) {
      setMode('register');
      setCode('');
    }
  }, [registration]);

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    if (!username.trim() || code.trim().length < 6) return;
    remember(username);
    emit.login(username.trim(), code.trim());
  };

  const handleRegisterStart = (e: React.FormEvent) => {
    e.preventDefault();
    if (!username.trim()) return;
    remember(username);
    trackEvent('register');
    emit.registerAccount(username.trim());
  };

  const handleConfirm = (e: React.FormEvent) => {
    e.preventDefault();
    if (code.trim().length < 6) return;
    emit.confirmAccount(username.trim(), code.trim());
  };

  const switchMode = (m: Mode) => {
    setMode(m);
    setCode('');
    setRegistration(null);
  };

  const handleShowRules = () => {
    setShowRules(true);
    trackEvent('rules_view');
  };

  return (
    <div className="max-w-sm mx-auto p-4 pt-12 min-h-screen">
      <h1 className="font-serif text-4xl text-center text-gold tracking-wide mb-1">Bridžik</h1>
      <p className="text-center text-green-dim text-sm mb-7">
        Prihlás sa kódom z aplikácie (napr. Google Authenticator).
      </p>

      <div className="flex mb-6 rounded-xl overflow-hidden border border-gold/20">
        <button
          onClick={() => switchMode('login')}
          className={`flex-1 py-2 text-sm font-serif tracking-wide ${
            mode === 'login' ? 'bg-gold text-table' : 'bg-header text-green-dim'
          }`}
        >
          Prihlásenie
        </button>
        <button
          onClick={() => switchMode('register')}
          className={`flex-1 py-2 text-sm font-serif tracking-wide ${
            mode === 'register' ? 'bg-gold text-table' : 'bg-header text-green-dim'
          }`}
        >
          Registrácia
        </button>
      </div>

      {mode === 'login' && (
        <form onSubmit={handleLogin} className="flex flex-col gap-4">
          <input
            autoFocus
            type="text"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            maxLength={40}
            placeholder="Používateľské meno"
            className={inputCls}
          />
          <input
            type="text"
            inputMode="numeric"
            value={code}
            onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
            maxLength={6}
            placeholder="6-miestny kód"
            className={`${inputCls} tracking-widest font-mono`}
          />
          <button
            type="submit"
            disabled={!username.trim() || code.trim().length < 6}
            className="py-3 rounded-xl bg-gold text-table font-serif font-semibold hover:bg-gold-bright disabled:opacity-40 transition-colors"
          >
            Prihlásiť
          </button>
        </form>
      )}

      {mode === 'register' && !registration && (
        <form onSubmit={handleRegisterStart} className="flex flex-col gap-4">
          <input
            autoFocus
            type="text"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            maxLength={40}
            placeholder="Zvoľ si používateľské meno"
            className={inputCls}
          />
          <button
            type="submit"
            disabled={!username.trim()}
            className="py-3 rounded-xl bg-gold text-table font-serif font-semibold hover:bg-gold-bright disabled:opacity-40 transition-colors"
          >
            Vytvoriť účet
          </button>
        </form>
      )}

      {mode === 'register' && registration && (
        <div className="flex flex-col gap-4">
          <p className="text-sm text-green-score">
            Naskenuj QR kód do autentifikačnej aplikácie a opíš aktuálny kód.
          </p>
          <div className="bg-white rounded-xl p-4 flex justify-center">
            <QRCodeSVG value={registration.otpauth_uri} size={176} />
          </div>
          <div className="text-xs text-green-dim text-center">
            Alebo zadaj ručne kľúč:
            <span className="block font-mono text-green-score break-all mt-1">
              {registration.secret}
            </span>
          </div>
          <form onSubmit={handleConfirm} className="flex flex-col gap-3">
            <input
              autoFocus
              type="text"
              inputMode="numeric"
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
              maxLength={6}
              placeholder="6-miestny kód"
              className={`${inputCls} tracking-widest font-mono`}
            />
            <button
              type="submit"
              disabled={code.trim().length < 6}
              className="py-3 rounded-xl bg-gold text-table font-serif font-semibold hover:bg-gold-bright disabled:opacity-40 transition-colors"
            >
              Potvrdiť a prihlásiť
            </button>
          </form>
        </div>
      )}

      {/* Rules are reachable before login — quiet link with the velvet divider motif. */}
      <div className="mt-10 flex items-center gap-3">
        <div className="h-px flex-1 bg-gradient-to-r from-transparent to-gold/20" />
        <button
          onClick={handleShowRules}
          className="uppercase tracking-[.13em] text-[10px] text-green-dim hover:text-gold transition-colors"
        >
          Pravidlá hry
        </button>
        <div className="h-px flex-1 bg-gradient-to-l from-transparent to-gold/20" />
      </div>

      {showRules && <RulesModal onClose={() => setShowRules(false)} />}
    </div>
  );
}
