'use client';

import { useEffect, useState } from 'react';
import {
  Container,
  Typography,
  Box,
  ToggleButtonGroup,
  ToggleButton,
  Card,
  CardContent,
  CircularProgress,
  Alert,
  Chip,
  Divider
} from '@mui/material';
import {
  EmojiEvents as TrophyIcon,
} from '@mui/icons-material';
import PersonIcon from '@mui/icons-material/Person';
import RiderAvatar from '@/components/RiderAvatar';

interface MotocrossStandingsRider {
  position: number;
  riderNumber: string;
  name: string;
  hometown: string;
  country: string;
  countryFlag: string;
  manufacturer: string;
  points: number;
  headshotUrl: string;
  profileUrl: string;
  pointsBehind: number;
}

interface MotocrossStandings {
  class: string;
  year: number;
  riders: MotocrossStandingsRider[];
  lastUpdated: string;
}

export default function MotocrossStandingsPage() {
  const [selectedClass, setSelectedClass] = useState<'450' | '250'>('450');
  const [standings, setStandings] = useState<MotocrossStandings | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchStandings();
  }, [selectedClass]);

  const fetchStandings = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/mx/standings/${selectedClass}`);
      if (!response.ok) {
        throw new Error('Failed to fetch standings');
      }
      const data: MotocrossStandings = await response.json();
      setStandings(data);
    } catch (err) {
      setError('Unable to load standings. Please try again later.');
      console.error('Error fetching MX standings:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleClassChange = (
    event: React.MouseEvent<HTMLElement>,
    newClass: '450' | '250' | null
  ) => {
    if (newClass !== null) {
      setSelectedClass(newClass);
    }
  };

  const getClassDisplayName = (className: string): string => {
    switch (className) {
      case '450':
        return '450MX';
      case '250':
        return '250MX';
      default:
        return className;
    }
  };

  const getPodiumColor = (position: number): string | undefined => {
    if (position === 1) return 'rgba(255, 215, 0, 0.15)'; // Gold
    if (position === 2) return 'rgba(192, 192, 192, 0.15)'; // Silver
    if (position === 3) return 'rgba(205, 127, 50, 0.15)'; // Bronze
    return undefined;
  };

  const getPositionColor = (position: number): string => {
    if (position === 1) return '#FFD700'; // Gold
    if (position === 2) return '#C0C0C0'; // Silver
    if (position === 3) return '#CD7F32'; // Bronze
    return '#ffffff'; // White for position 4+
  };

  if (loading) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Box display="flex" justifyContent="center" py={8}>
          <CircularProgress sx={{ color: '#ff7f00' }} />
        </Box>
      </Container>
    );
  }

  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      {/* SEO Content - Hidden but crawlable */}
      <Box component="section" sx={{ position: 'absolute', left: '-10000px', width: '1px', height: '1px', overflow: 'hidden' }}>
        <h1>2026 Lucas Oil AMA Pro Motocross Championship Standings</h1>
        <p>
          View the official championship standings for the 2026 Lucas Oil AMA Pro Motocross season.
          Track rider positions, points totals, and championship battles across the 450MX and 250MX classes.
        </p>
        <p>
          Our standings page provides comprehensive information including rider rankings, points accumulated,
          points behind the leader, hometown, manufacturer, and country. Updated after every national to reflect
          the latest championship positions.
        </p>
        <p>
          450MX features the premier class with the sport's top riders competing for the outdoor national championship.
          250MX showcases rising talent competing across all 11 rounds of the summer series. Follow every position
          change throughout the Pro Motocross Championship season.
        </p>
      </Box>

      {/* Header */}
      <Box sx={{ mb: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3, flexWrap: 'wrap', gap: 2 }}>
          <Box sx={{ flex: 1 }}>
            <Typography
              component="h1"
              variant="h4"
              sx={{
                fontWeight: 700,
                display: 'flex',
                alignItems: 'center',
                gap: 2,
                mb: 1,
              }}
            >
              <TrophyIcon sx={{ fontSize: 40, color: '#ff7f00' }} />
              2026 Pro Motocross Championship Standings
            </Typography>
            <Typography variant="body1" color="text.secondary" sx={{ mb: 2 }}>
              Current championship points and rankings for 450MX and 250MX classes. Updated after each national.
            </Typography>
          </Box>

          {/* Class Toggle */}
          <ToggleButtonGroup
            value={selectedClass}
            exclusive
            onChange={handleClassChange}
            aria-label="class selection"
            sx={{
              '& .MuiToggleButton-root.Mui-selected': {
                bgcolor: '#ff7f00',
                color: '#000',
                '&:hover': {
                  bgcolor: '#ffa040',
                },
              },
            }}
          >
            <ToggleButton value="450">450MX</ToggleButton>
            <ToggleButton value="250">250MX</ToggleButton>
          </ToggleButtonGroup>
        </Box>

        {standings && !loading && (
          <Box sx={{ mb: 3 }}>
            <Typography variant="h6" color="text.secondary" fontWeight={600}>
              {getClassDisplayName(selectedClass)}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              2026 Lucas Oil AMA Pro Motocross Championship
            </Typography>
          </Box>
        )}
      </Box>

      {loading && (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <CircularProgress sx={{ color: '#ff7f00' }} />
        </Box>
      )}

      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      {standings && standings.riders.length === 0 && (
        <Alert severity="info" sx={{ mb: 3 }}>
          No standings available for {getClassDisplayName(selectedClass)} yet.
        </Alert>
      )}

      {standings && standings.riders.length > 0 && (
        <>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {standings.riders.map((rider) => (
              <Card
                key={rider.position}
                sx={{
                  bgcolor: getPodiumColor(rider.position) || 'background.paper',
                  border: rider.position <= 3 ? `2px solid ${getPositionColor(rider.position)}` : '1px solid rgba(255, 255, 255, 0.12)',
                  transition: 'all 0.3s ease',
                  '&:hover': {
                    bgcolor: 'rgba(255, 127, 0, 0.05)',
                    transform: 'translateY(-2px)',
                    boxShadow: '0 4px 20px rgba(255, 127, 0, 0.2)',
                  },
                }}
              >
                <CardContent sx={{ py: { xs: 1.5, md: 2 }, px: { xs: 1.5, md: 3 }, '&:last-child': { pb: { xs: 1.5, md: 2 } } }}>
                  {/* Mobile View */}
                  <Box sx={{ display: { xs: 'flex', md: 'none' }, gap: 1.5, alignItems: 'flex-start' }}>
                    {/* Position & Trophy */}
                    <Box sx={{ textAlign: 'center', minWidth: 40 }}>
                      <Typography
                        variant="h5"
                        fontWeight={700}
                        sx={{
                          color: getPositionColor(rider.position),
                          textShadow: rider.position <= 3 ? `0 0 10px ${getPositionColor(rider.position)}40` : 'none',
                          lineHeight: 1,
                        }}
                      >
                        {rider.position}
                      </Typography>
                      {rider.position <= 3 && (
                        <TrophyIcon
                          sx={{
                            fontSize: 18,
                            color: getPositionColor(rider.position),
                            mt: 0.5,
                          }}
                        />
                      )}
                    </Box>

                    {/* Avatar & Number */}
                    <Box sx={{ position: 'relative' }}>
                      <RiderAvatar
                        riderName={rider.name}
                        photoUrl={rider.headshotUrl}
                        alt={rider.name}
                        sx={{
                          width: 60,
                          height: 60,
                          border: rider.position <= 3 ? `2px solid ${getPositionColor(rider.position)}` : '2px solid #ff7f00',
                        }}
                      >
                        <PersonIcon />
                      </RiderAvatar>
                      {rider.riderNumber && (
                        <Box
                          sx={{
                            position: 'absolute',
                            bottom: -6,
                            left: '50%',
                            transform: 'translateX(-50%)',
                            bgcolor: rider.position === 1 ? '#dc143c' : '#000',
                            color: '#fff',
                            px: 1,
                            py: 0.25,
                            borderRadius: 0.5,
                            minWidth: 30,
                            textAlign: 'center',
                            fontWeight: 700,
                            fontSize: '0.75rem',
                            border: '2px solid #fff',
                            boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
                          }}
                        >
                          {rider.riderNumber}
                        </Box>
                      )}
                    </Box>

                    {/* Rider Info */}
                    <Box sx={{ flex: 1, minWidth: 0 }}>
                      <Typography variant="subtitle1" fontWeight={700} noWrap>
                        {rider.name}
                      </Typography>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 0.5 }}>
                        {rider.countryFlag && (
                          <img
                            src={rider.countryFlag}
                            alt={rider.country}
                            style={{ width: 16, height: 12 }}
                          />
                        )}
                        <Typography variant="caption" color="text.secondary" noWrap>
                          {rider.country}
                        </Typography>
                      </Box>
                      <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }} noWrap>
                        {rider.hometown}
                      </Typography>

                      {/* Mobile-specific manufacturer and points row */}
                      <Box sx={{ display: 'flex', gap: 2, mt: 1 }}>
                        <Box>
                          <Typography variant="caption" color="text.secondary" sx={{ fontSize: '0.65rem' }}>
                            Manufacturer
                          </Typography>
                          <Typography variant="body2" fontWeight={700}>
                            {rider.manufacturer}
                          </Typography>
                        </Box>
                        <Box>
                          <Typography variant="caption" color="text.secondary" sx={{ fontSize: '0.65rem' }}>
                            Total Points
                          </Typography>
                          <Typography variant="h6" fontWeight={700} sx={{ color: '#ff7f00', lineHeight: 1.2 }}>
                            {rider.points}
                          </Typography>
                        </Box>
                        {rider.pointsBehind > 0 && (
                          <Box>
                            <Typography variant="caption" color="text.secondary" sx={{ fontSize: '0.65rem' }}>
                              Points Behind
                            </Typography>
                            <Typography variant="body2" fontWeight={600} sx={{ lineHeight: 1.2 }}>
                              {rider.pointsBehind === 0 ? '—' : `-${rider.pointsBehind}`}
                            </Typography>
                          </Box>
                        )}
                      </Box>
                    </Box>
                  </Box>

                  {/* Desktop View */}
                  <Box sx={{ display: { xs: 'none', md: 'flex' }, alignItems: 'center', gap: 3, flexWrap: 'wrap' }}>
                    {/* Position */}
                    <Box sx={{ minWidth: 60, textAlign: 'center' }}>
                      <Typography
                        variant="h4"
                        fontWeight={700}
                        sx={{
                          color: getPositionColor(rider.position),
                          textShadow: rider.position <= 3 ? `0 0 10px ${getPositionColor(rider.position)}40` : 'none',
                        }}
                      >
                        {rider.position}
                      </Typography>
                      {rider.position <= 3 && (
                        <TrophyIcon
                          sx={{
                            fontSize: 24,
                            color: getPositionColor(rider.position),
                            mt: 0.5,
                          }}
                        />
                      )}
                    </Box>

                    <Divider orientation="vertical" flexItem />

                    {/* Rider Photo */}
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, minWidth: 150 }}>
                      <RiderAvatar
                        riderName={rider.name}
                        photoUrl={rider.headshotUrl}
                        alt={rider.name}
                        sx={{
                          width: 64,
                          height: 64,
                          border: rider.position <= 3 ? `3px solid ${getPositionColor(rider.position)}` : '2px solid #ff7f00',
                        }}
                      >
                        <PersonIcon />
                      </RiderAvatar>

                      {/* Rider Number Plate */}
                      {rider.riderNumber && (
                        <Box
                          sx={{
                            bgcolor: rider.position === 1 ? '#dc143c' : '#000',
                            color: '#fff',
                            px: 2,
                            py: 1,
                            borderRadius: 1,
                            minWidth: 50,
                            textAlign: 'center',
                            fontWeight: 700,
                            fontSize: '1.25rem',
                            border: '2px solid #fff',
                            boxShadow: rider.position === 1 ? '0 0 15px rgba(220, 20, 60, 0.6)' : '0 2px 4px rgba(0,0,0,0.3)',
                          }}
                        >
                          {rider.riderNumber}
                        </Box>
                      )}
                    </Box>

                    {/* Rider Info */}
                    <Box sx={{ flex: '1 1 300px' }}>
                      <Typography variant="h6" fontWeight={700}>
                        {rider.name}
                      </Typography>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 0.5 }}>
                        {rider.countryFlag && (
                          <img
                            src={rider.countryFlag}
                            alt={rider.country}
                            style={{ width: 20, height: 15 }}
                          />
                        )}
                        <Typography variant="body2" color="text.secondary">
                          {rider.country}
                        </Typography>
                      </Box>
                      <Typography variant="caption" color="text.secondary">
                        {rider.hometown}
                      </Typography>
                    </Box>

                    {/* Manufacturer */}
                    <Box sx={{ minWidth: 120, textAlign: 'center' }}>
                      <Typography variant="body2" color="text.secondary" sx={{ mb: 0.5 }}>
                        Manufacturer
                      </Typography>
                      <Typography variant="h6" fontWeight={700}>
                        {rider.manufacturer}
                      </Typography>
                    </Box>

                    <Divider orientation="vertical" flexItem />

                    {/* Points */}
                    <Box sx={{ minWidth: 120, textAlign: 'center' }}>
                      <Typography variant="body2" color="text.secondary" sx={{ mb: 0.5 }}>
                        Total Points
                      </Typography>
                      <Typography variant="h5" fontWeight={700} sx={{ color: '#ff7f00' }}>
                        {rider.points}
                      </Typography>
                    </Box>

                    {/* Points Behind */}
                    <Box sx={{ minWidth: 120, textAlign: 'center' }}>
                      <Typography variant="body2" color="text.secondary" sx={{ mb: 0.5 }}>
                        Points Behind
                      </Typography>
                      <Typography variant="h6" fontWeight={600}>
                        {rider.pointsBehind === 0 ? '—' : `-${rider.pointsBehind}`}
                      </Typography>
                    </Box>
                  </Box>
                </CardContent>
              </Card>
            ))}
          </Box>

          {/* Last Updated */}
          <Box sx={{ mt: 2, textAlign: 'right' }}>
            <Typography variant="caption" sx={{ color: 'text.secondary' }}>
              Last updated: {new Date(standings.lastUpdated).toLocaleString()}
            </Typography>
          </Box>

          {/* Data Source Attribution */}
          <Box sx={{ mt: 3, p: 2, bgcolor: 'background.paper', borderRadius: 1, border: '1px solid', borderColor: 'divider' }}>
            <Typography variant="body2" sx={{ color: 'text.secondary', textAlign: 'center' }}>
              Standings data sourced from{' '}
              <a
                href="https://racerxonline.com/mx/points"
                target="_blank"
                rel="noopener noreferrer"
                style={{ color: '#ff7f00', textDecoration: 'none', fontWeight: 'bold' }}
              >
                Racer X Online
              </a>
            </Typography>
          </Box>
        </>
      )}
    </Container>
  );
}
