import { useState, type FormEvent } from 'react';
import { Navigate, useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/context';
import { APP_ID } from '../api/config';
import { Button } from '../components/buttons';
import { Card, Input } from '../components/reusable';

/** Login gate. Redirects to /orders once authenticated. */
export function LoginPage() {
  const { authed, login } = useAuth();
  const navigate = useNavigate();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [orgId, setOrgId] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (authed) return <Navigate to="/orders" replace />;

  async function submit(e: FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      await login(email, password, orgId || undefined);
      navigate('/orders', { 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-5">
          <h1 className="m-0 text-2xl font-extrabold text-strong tracking-[-0.02em]">Krishna Sales</h1>
          <p className="m-0 text-sm text-faint">Field Sales console · Sandbox {APP_ID}</p>
        </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 />
          <Input label="Org ID" hint="Optional" value={orgId} onChange={(e) => setOrgId(e.target.value)} />
          {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>
  );
}
