import { useState, type FormEvent } from 'react';
import { Navigate, useLocation, useNavigate } from 'react-router-dom';
import { extractApiError } from '@/api/client';
import { useAuth } from '@/hooks/useAuth';
import { FormField, TextInput } from '@/components/FormField';

interface LocationState {
  from?: string;
}

export function LoginPage(): JSX.Element {
  const { login, status, user } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const fromPath = (location.state as LocationState | null)?.from;

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Already authenticated → bounce to engagements (e.g. user navigates back to /login).
  // Returning <Navigate> instead of calling navigate() during render avoids the
  // "Cannot update a component while rendering a different component" warning.
  if (status === 'authenticated' && user) {
    return <Navigate to={fromPath ?? '/engagements'} replace />;
  }

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      await login(username, password);
      navigate(fromPath ?? '/engagements', { replace: true });
    } catch (err) {
      setError(extractApiError(err, 'Invalid credentials'));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-cloud flex items-center justify-center px-md">
      <div className="w-full max-w-md card-product flex flex-col gap-lg">
        {/* Chevron echo of the brand mark */}
        <div className="flex items-center gap-sm">
          <span className="inline-block h-8 w-8 rotate-12 bg-primary" aria-hidden />
          <h1 className="text-[32px] font-medium leading-none">Mimic</h1>
        </div>
        <p className="text-[16px] text-charcoal">Sign in to access your engagements.</p>

        <form onSubmit={onSubmit} noValidate className="flex flex-col gap-md">
          <FormField label="Username" htmlFor="login-username" required>
            <TextInput
              id="login-username"
              name="username"
              autoComplete="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
          </FormField>

          <FormField label="Password" htmlFor="login-password" required>
            <TextInput
              id="login-password"
              type="password"
              name="password"
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </FormField>

          {error ? (
            <div role="alert" data-testid="login-error" className="text-[14px] text-bloom-deep">
              {error}
            </div>
          ) : null}

          <button type="submit" className="btn-primary" disabled={submitting}>
            {submitting ? 'Signing in…' : 'Sign in'}
          </button>
        </form>
      </div>
    </div>
  );
}
