import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
import { authClient } from '../lib/grpc';
import { SESSION_EXPIRED_KEY } from '../lib/auth';

/** Read and clear the session-expired flag set by the gRPC interceptor on UNAUTHENTICATED / token expiry */
function consumeSessionExpiredFlag(): boolean {
  const expired = sessionStorage.getItem(SESSION_EXPIRED_KEY) === '1';
  if (expired) sessionStorage.removeItem(SESSION_EXPIRED_KEY);
  return expired;
}

export function LoginPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [sessionExpired] = useState(consumeSessionExpiredFlag);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const { login, authenticated } = useAuth();
  const navigate = useNavigate();

  if (authenticated) {
    navigate('/trading', { replace: true });
    return null;
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      const response = await authClient.login({ username, password });
      login(response.accessToken, response.refreshToken);
      navigate('/trading', { replace: true });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Login failed');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex items-center justify-center min-h-screen bg-[var(--color-bg-primary)]">
      <div className="w-full max-w-sm p-6 rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
        <h1 className="text-lg font-medium text-center mb-1">
          Foxhunt Trading System
        </h1>
        <p className="text-xs text-[var(--color-text-secondary)] text-center mb-6">
          Sign in to access the dashboard
        </p>

        {sessionExpired && (
          <p className="text-xs text-[var(--color-yellow,#ca8a04)] bg-[var(--color-bg-primary)] border border-[var(--color-border)] rounded px-3 py-2 mb-4 text-center">
            Your session has expired. Please sign in again.
          </p>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-xs text-[var(--color-text-secondary)] mb-1">
              Username
            </label>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              autoComplete="username"
              required
              className="w-full px-3 py-2 text-sm rounded border border-[var(--color-border)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent)]"
            />
          </div>
          <div>
            <label className="block text-xs text-[var(--color-text-secondary)] mb-1">
              Password
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="current-password"
              required
              className="w-full px-3 py-2 text-sm rounded border border-[var(--color-border)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent)]"
            />
          </div>

          {error && (
            <p className="text-xs text-[var(--color-red)]">{error}</p>
          )}

          <button
            type="submit"
            disabled={loading}
            className="w-full py-2 text-sm font-medium rounded bg-[var(--color-accent)] text-white hover:bg-blue-600 disabled:opacity-50"
          >
            {loading ? 'Signing in...' : 'Sign In'}
          </button>
        </form>
      </div>
    </div>
  );
}
