import React, { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { Box, CircularProgress, Typography, Alert, Button } from '@mui/material';

const LoginCallback: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { login } = useAuth();
  const [error, setError] = useState<string>('');

  useEffect(() => {
    const handleCallback = async () => {
      const code = searchParams.get('code');
      const errorParam = searchParams.get('error');

      if (errorParam) {
        setError(`Authentifizierungsfehler: ${errorParam}`);
        return;
      }

      if (!code) {
        setError('Kein Autorisierungscode erhalten');
        return;
      }

      try {
        await login(code);
        // Redirect to dashboard on success
        navigate('/dashboard', { replace: true });
      } catch (err) {
        console.error('Login callback error:', err);
        setError(
          err instanceof Error
            ? err.message
            : 'Anmeldung fehlgeschlagen. Bitte versuchen Sie es erneut.'
        );
      }
    };

    handleCallback();
  }, [searchParams, login, navigate]);

  if (error) {
    return (
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          minHeight: '100vh',
          padding: 3,
        }}
      >
        <Alert
          severity="error"
          sx={{
            maxWidth: 500,
            mb: 2,
            width: '100%',
          }}
        >
          {error}
        </Alert>
        <Button
          variant="contained"
          onClick={() => navigate('/login')}
        >
          Zurück zur Anmeldung
        </Button>
      </Box>
    );
  }

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        minHeight: '100vh',
        gap: 2,
      }}
    >
      <CircularProgress size={60} />
      <Typography variant="h6" color="text.secondary">
        Anmeldung wird abgeschlossen...
      </Typography>
    </Box>
  );
};

export default LoginCallback;
