import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';
import {
  Box,
  Button,
  Typography,
  Container,
  Fade,
} from '@mui/material';
import HomeIcon from '@mui/icons-material/Home';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';

export default function Custom404() {
  const router = useRouter();
  const [countdown, setCountdown] = useState(5);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    let rafId;
    let timeoutId;

    if (typeof window !== 'undefined' && 'requestAnimationFrame' in window) {
      rafId = window.requestAnimationFrame(() => {
        setMounted(true);
      });
    } else {
      // Fallback for environments without requestAnimationFrame
      timeoutId = setTimeout(() => setMounted(true), 0);
    }

    return () => {
      if (rafId !== undefined && typeof window !== 'undefined' && 'cancelAnimationFrame' in window) {
        window.cancelAnimationFrame(rafId);
      }
      if (timeoutId !== undefined) {
        clearTimeout(timeoutId);
      }
    };
  }, []);

  useEffect(() => {
    const interval = setInterval(() => {
      setCountdown((prev) => prev - 1);
    }, 1000);

    const timer = setTimeout(() => {
      router.back();
    }, 5000);

    return () => {
      clearInterval(interval);
      clearTimeout(timer);
    };
  }, [router]);

  if (!mounted) return null;

  return (
    <Fade in timeout={800}>
      <Box
        sx={{
          minHeight: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: 'linear-gradient(135deg, #1a237e 0%, #1565c0 50%, #0d47a1 100%)',
          position: 'relative',
          overflow: 'hidden',
          '&::before': {
            content: '""',
            position: 'absolute',
            width: '400px',
            height: '400px',
            background: 'rgba(255, 255, 255, 0.05)',
            borderRadius: '50%',
            top: '-100px',
            right: '-100px',
            animation: 'float 6s ease-in-out infinite',
          },
          '&::after': {
            content: '""',
            position: 'absolute',
            width: '300px',
            height: '300px',
            background: 'rgba(255, 255, 255, 0.03)',
            borderRadius: '50%',
            bottom: '-50px',
            left: '-50px',
            animation: 'float 8s ease-in-out infinite reverse',
          },
          '@keyframes float': {
            '0%, 100%': { transform: 'translateY(0px)' },
            '50%': { transform: 'translateY(30px)' },
          },
        }}
      >
        <Container maxWidth="sm" sx={{ position: 'relative', zIndex: 1 }}>
          <Box sx={{ textAlign: 'center' }}>
            <Box
              sx={{
                mb: 3,
                display: 'inline-block',
                fontSize: '120px',
                fontWeight: 'bold',
                background: 'linear-gradient(135deg, #64B5F6 0%, #42A5F5 100%)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                backgroundClip: 'text',
                animation: 'pulse 2s ease-in-out infinite',
                '@keyframes pulse': {
                  '0%, 100%': { opacity: 1 },
                  '50%': { opacity: 0.7 },
                },
              }}
            >
              404
            </Box>

            <Typography
              variant="h3"
              sx={{
                color: '#ffffff',
                fontWeight: 'bold',
                mb: 2,
                letterSpacing: '-1px',
              }}
            >
              ¡Página No Encontrada!
            </Typography>

            <Typography
              variant="body1"
              sx={{
                color: 'rgba(255, 255, 255, 0.85)',
                mb: 3,
                fontSize: '1.1rem',
                lineHeight: 1.6,
              }}
            >
              Parece que la página que buscas se perdió en el universo digital.
              No te preocupes, te ayudaremos a encontrar el camino de vuelta.
            </Typography>

            <Box
              sx={{
                background: 'rgba(255, 255, 255, 0.1)',
                backdrop: 'blur(10px)',
                border: '1px solid rgba(255, 255, 255, 0.2)',
                borderRadius: '12px',
                padding: '20px',
                mb: 4,
              }}
            >
              <Typography
                variant="body2"
                sx={{
                  color: 'rgba(255, 255, 255, 0.9)',
                  fontSize: '0.95rem',
                }}
              >
                Redirigiendo en{' '}
                <span
                  style={{
                    fontSize: '1.2rem',
                    fontWeight: 'bold',
                    color: '#64B5F6',
                  }}
                >
                  {countdown}s
                </span>
              </Typography>
            </Box>

            <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
              <Button
                component={Link}
                href="/"
                variant="contained"
                startIcon={<HomeIcon />}
                sx={{
                  background: 'linear-gradient(135deg, #64B5F6 0%, #42A5F5 100%)',
                  color: '#ffffff',
                  px: 4,
                  py: 1.5,
                  fontWeight: 600,
                  fontSize: '1rem',
                  borderRadius: '8px',
                  textTransform: 'none',
                  transition: 'all 0.3s ease',
                  '&:hover': {
                    transform: 'translateY(-3px)',
                    boxShadow: '0 8px 24px rgba(100, 181, 246, 0.4)',
                  },
                }}
              >
                Ir al Inicio
              </Button>

              <Button
                onClick={() => router.back()}
                variant="outlined"
                startIcon={<ArrowBackIcon />}
                sx={{
                  borderColor: 'rgba(255, 255, 255, 0.5)',
                  color: '#ffffff',
                  px: 4,
                  py: 1.5,
                  fontWeight: 600,
                  fontSize: '1rem',
                  borderRadius: '8px',
                  textTransform: 'none',
                  transition: 'all 0.3s ease',
                  '&:hover': {
                    borderColor: '#64B5F6',
                    backgroundColor: 'rgba(100, 181, 246, 0.1)',
                    transform: 'translateY(-3px)',
                  },
                }}
              >
                Volver Atrás
              </Button>
            </Box>
          </Box>
        </Container>
      </Box>
    </Fade>
  );
}