import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Container, Typography, Box, Alert } from '@mui/material';
import { useAuth } from '../../contexts/AuthContext';
import { EmailLoginForm } from './EmailLoginForm';
import { EmailCredentials } from '../../services/auth/authService';
import { logger } from '../../debugConfig';

const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const { user, signIn } = useAuth();
  const [error, setError] = useState<string | null>(null);

  logger.debug('login-page', '🔍 Login page loaded', { 
    hasUser: !!user
  });

  useEffect(() => {
    if (user) {
      navigate('/dashboard');
    }
  }, [user, navigate]);

  const handleLogin = async (credentials: EmailCredentials) => {
    try {
      setError(null);
      await signIn(credentials.email, credentials.password);
      navigate('/dashboard');
    } catch (error) {
      logger.error('login-page', '❌ Login failed', error);
      setError(error instanceof Error ? error.message : 'Login failed');
      throw error;
    }
  };

  if (user) {
    return null;
  }

  return (
    <Container 
      sx={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        minHeight: '100vh',
        gap: 4
      }}
    >
      <Typography variant="h2" component="h1" gutterBottom>
        ClassroomCopilot.ai
      </Typography>

      <Typography variant="h4" gutterBottom>
        Login
      </Typography>

      {error && (
        <Alert severity="error" sx={{ width: '100%', maxWidth: 400 }}>
          {error}
        </Alert>
      )}

      <Box sx={{ width: '100%', maxWidth: 400 }}>
        <EmailLoginForm 
          role="email_teacher"
          onSubmit={handleLogin}
        />
      </Box>
    </Container>
  );
};

export default LoginPage; 
