import { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  Container,
  Box,
  Paper,
  Button,
  Typography,
  CircularProgress,
  Fade,
} from '@mui/material';
import { LocalFireDepartment, Login as LoginIcon } from '@mui/icons-material';
import { authService } from '../services/auth';
import { useAuth } from '../contexts/AuthContext';

function Login() {
  const navigate = useNavigate();
  const location = useLocation();
  const { isAuthenticated, isLoading } = useAuth();
  const [isRedirecting, setIsRedirecting] = useState(false);

  // Redirect to dashboard if already authenticated
  useEffect(() => {
    if (isAuthenticated) {
      setIsRedirecting(true);
      const rawFrom = (location.state as any)?.from;
      const from =
        rawFrom && rawFrom.startsWith('/') && !rawFrom.startsWith('//')
          ? rawFrom
          : '/dashboard';
      navigate(from, { replace: true });
    }
  }, [isAuthenticated, navigate, location.state]);

  const handleLogin = () => {
    try {
      // Persist the intended destination so LoginCallback can restore it
      // after the full-page Authentik redirect round-trip.
      // Validate that from is a safe internal path before storing it.
      const rawFrom = (location.state as any)?.from;
      if (rawFrom && rawFrom.startsWith('/') && !rawFrom.startsWith('//')) {
        sessionStorage.setItem('auth_redirect_from', rawFrom);
      }
      const authUrl = authService.getAuthUrl();
      window.location.href = authUrl;
    } catch (error) {
      console.error('Failed to initiate login:', error);
    }
  };

  if (isLoading || isRedirecting) {
    return (
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          minHeight: '100vh',
          bgcolor: 'background.default',
        }}
      >
        <Box sx={{ textAlign: 'center' }}>
          <CircularProgress size={60} />
          <Typography variant="body1" sx={{ mt: 2 }} color="text.secondary">
            {isRedirecting ? 'Weiterleitung...' : 'Lade...'}
          </Typography>
        </Box>
      </Box>
    );
  }

  return (
    <Container component="main" maxWidth="xs">
      <Box
        sx={{
          marginTop: 8,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          minHeight: '100vh',
        }}
      >
        <Fade in={true} timeout={800}>
          <Paper
            elevation={3}
            sx={{
              padding: 4,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              width: '100%',
            }}
          >
            <LocalFireDepartment sx={{ fontSize: 60, color: 'primary.main', mb: 2 }} />
            <Typography component="h1" variant="h5" gutterBottom>
              Feuerwehr Dashboard
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 3, textAlign: 'center' }}>
              Bitte melden Sie sich mit Ihrem Authentik-Konto an
            </Typography>

            <Button
              fullWidth
              variant="contained"
              size="large"
              onClick={handleLogin}
              startIcon={<LoginIcon />}
              sx={{ mt: 2 }}
              aria-label="Mit Authentik anmelden"
            >
              Mit Authentik anmelden
            </Button>
          </Paper>
        </Fade>

        <Box
          component="footer"
          sx={{
            mt: 'auto',
            py: 3,
          }}
        >
          <Typography variant="caption" color="text.secondary" align="center" display="block">
            Feuerwehr Dashboard v0.0.1
          </Typography>
          <Typography variant="caption" color="text.secondary" align="center" display="block">
            {new Date().getFullYear()}
          </Typography>
        </Box>
      </Box>
    </Container>
  );
}

export default Login;
