'use client';

import { useEffect, useRef, useState } from 'react';
import { Lock } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';

/**
 * "Welcome back — enter your code."
 * Shown over the page (which stays mounted underneath, so nothing typed is lost)
 * when the session has been idle, the PC was asleep/off, or the tab sat overnight.
 * Only the 6-digit authenticator code is asked for — no email, no password.
 * "Sign in as someone else" is the escape hatch (it ends the session).
 */
export default function LockScreen() {
  const { user, unlock, logout } = useAuth();
  const [code, setCode] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const input = useRef<HTMLInputElement>(null);

  useEffect(() => { input.current?.focus(); }, []);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError(null); setBusy(true);
    try {
      await unlock(code);
      setCode('');
    } catch (err) {
      const m = (err as Error).message;
      if (m === 'FORBIDDEN') return; // session ended entirely → layout redirects to /login
      setError(m === 'ACCOUNT_LOCKED' ? 'Too many wrong codes — account locked for 15 minutes.'
        : m === 'TOO_MANY_ATTEMPTS' ? 'Too many attempts — wait a few minutes.'
        : 'That code is wrong or expired. Try the next one.');
      setCode(''); input.current?.focus();
    } finally { setBusy(false); }
  }

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-brand-charcoal/85 backdrop-blur-md p-4 animate-fadeIn">
      <form onSubmit={submit} className="w-full max-w-sm bg-white rounded-2xl shadow-2xl p-8 text-center animate-scaleIn">
        <div className="w-12 h-12 mx-auto rounded-full bg-brand-red/10 text-brand-red flex items-center justify-center mb-3"><Lock size={22} /></div>
        <h2 className="font-bold text-base">Welcome back{user?.name ? `, ${user.name.split(' ')[0]}` : ''}</h2>
        <p className="text-xs text-gray-500 mt-1">Your session was locked while you were away. Enter the 6-digit code from your authenticator app to continue right where you left off.</p>
        {user?.email && <p className="text-[11px] text-gray-400 mt-2">{user.email}</p>}
        <input ref={input} inputMode="numeric" autoComplete="one-time-code" maxLength={6} required value={code}
          onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
          className="mt-4 w-full border border-brand-border rounded-lg px-3 py-3 text-center text-xl tracking-[0.5em] focus:outline-none focus:border-brand-red" placeholder="••••••" />
        {error && <p className="text-xs text-brand-red mt-2">{error}</p>}
        <button disabled={busy || code.length !== 6} className="mt-4 w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
          {busy ? 'Unlocking…' : 'Unlock'}
        </button>
        <button type="button" onClick={logout} className="mt-3 text-[11px] text-gray-400 hover:text-brand-red transition-colors">Not you? Sign in as a different user</button>
      </form>
    </div>
  );
}
