import React, { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useIsAuthenticated, useAuthLoading } from '../../stores';
import { LoginForm } from '../../components/domain/auth';
import { PublicLayout } from '../../components/layout';

const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  
  const loading = useAuthLoading();
  const isAuthenticated = useIsAuthenticated();

  const from = (location.state as any)?.from?.pathname || '/app';

  useEffect(() => {
    if (isAuthenticated && !loading) {
      // Add a small delay to ensure the auth state has fully settled
      setTimeout(() => {
        navigate(from, { replace: true });
      }, 100);
    }
  }, [isAuthenticated, loading, navigate, from]);

  const handleLoginSuccess = () => {
    navigate(from, { replace: true });
  };

  const handleRegisterClick = () => {
    navigate('/register');
  };

  return (
    <PublicLayout 
      variant="centered"
      maxWidth="md"
      headerProps={{
        showThemeToggle: true,
        showAuthButtons: false,
        variant: "minimal"
      }}
    >
      <LoginForm
        onSuccess={handleLoginSuccess}
        onRegisterClick={handleRegisterClick}
        className="mx-auto"
      />
    </PublicLayout>
  );
};

export default LoginPage;