import { useState, type FormEvent } from 'react';
import { Navigate, useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/context';
import { Button } from '../components/buttons';
import { Card, Input } from '../components/reusable';
import { getDefaultRoute } from '../auth/ProtectedRoute';
import logo from '../assets/logo.png';

/** Login gate. Redirects to default route once authenticated. */
export function LoginPage() {
  const { authed, login, roles, isAdmin } = useAuth();
  const navigate = useNavigate();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (authed) return <Navigate to={getDefaultRoute(roles, isAdmin)} replace />;

  async function submit(e: FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      await login(email, password);
      
      // Wait for a tick so useAuth state updates (if necessary) or we can just navigate to root 
      // which will redirect. But since we need the updated roles, navigating to root is safest.
      navigate('/', { replace: true });
    } catch (err) {
      setError((err as { message?: string })?.message ?? 'Login failed');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4 bg-app">
      <Card className="w-full max-w-[400px]">
        <div className="flex flex-col gap-1 mb-6 items-center text-center">
          <img src={logo} alt="Logo" className="h-20 w-auto object-contain mb-2" />
          <h1 className="m-0 text-2xl font-extrabold text-strong tracking-[-0.02em]">Krishna Sales</h1>
        </div>
        <form onSubmit={submit} className="flex flex-col gap-4">
          <Input label="Email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required autoFocus />
          <Input label="Password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />

          {error && <div className="text-xs text-ruby-600 font-medium">{error}</div>}
          <Button type="submit" full disabled={busy}>
            {busy ? 'Signing in…' : 'Sign in'}
          </Button>
        </form>
      </Card>
    </div>
  );
}
