import { Box, Chip, Stack, Paper, Divider, useTheme } from '@mui/material';
import { 
  Cloud, 
  WbSunny, 
  Thunderstorm, 
  AcUnit, 
  Opacity,
  Air,
  WbCloudy,
  Grain,
  Foggy
} from '@mui/icons-material';
import { LineChart } from '@mui/x-charts/LineChart';
import GenericWidget from './GenericWidget';

function WeatherWidget({ data, sx }) {
  const theme = useTheme();

  // Weather icon mapping based on Open-Meteo icon types
  const getWeatherIcon = (iconType) => {
    const iconMap = {
      'sunny': <WbSunny sx={{ fontSize: 40, color: theme.palette.warning.main }} />,
      'partly_cloudy': <WbCloudy sx={{ fontSize: 40, color: theme.palette.grey[600] }} />,
      'cloudy': <Cloud sx={{ fontSize: 40, color: theme.palette.grey[500] }} />,
      'foggy': <Foggy sx={{ fontSize: 40, color: theme.palette.grey[400] }} />,
      'rainy': <Grain sx={{ fontSize: 40, color: theme.palette.info.main }} />,
      'snowy': <AcUnit sx={{ fontSize: 40, color: theme.palette.info.light }} />,
      'stormy': <Thunderstorm sx={{ fontSize: 40, color: theme.palette.error.main }} />
    };
    return iconMap[iconType] || <Cloud sx={{ fontSize: 40 }} />;
  };

  // Small icon for forecast
  const getForecastIcon = (iconType) => {
    const iconMap = {
      'sunny': <WbSunny sx={{ fontSize: 24, color: theme.palette.warning.main }} />,
      'partly_cloudy': <WbCloudy sx={{ fontSize: 24, color: theme.palette.grey[600] }} />,
      'cloudy': <Cloud sx={{ fontSize: 24, color: theme.palette.grey[500] }} />,
      'foggy': <Foggy sx={{ fontSize: 24, color: theme.palette.grey[400] }} />,
      'rainy': <Grain sx={{ fontSize: 24, color: theme.palette.info.main }} />,
      'snowy': <AcUnit sx={{ fontSize: 24, color: theme.palette.info.light }} />,
      'stormy': <Thunderstorm sx={{ fontSize: 24, color: theme.palette.error.main }} />
    };
    return iconMap[iconType] || <Cloud sx={{ fontSize: 24 }} />;
  };

  // Format date for display
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });
  };

  // Format short date for charts based on user preference
  const formatChartDate = (dateStr) => {
    const date = new Date(dateStr);
    const format = import.meta.env.REACT_APP_CHART_DATE_FORMAT || 'MM/DD/YYYY';
    
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const year = date.getFullYear();
    
    switch(format) {
      case 'MM/DD/YYYY':
        return `${month}/${day}/${year}`;
      case 'DD/MM/YYYY':
        return `${day}/${month}/${year}`;
      case 'MM/DD':
        return `${month}/${day}`;
      case 'DD/MM':
        return `${day}/${month}`;
      default:
        return `${month}/${day}/${year}`; // Default to MM/DD/YYYY
    }
  };

  if (!data || data.error) {
    return (
      <GenericWidget title="Weather" sx={{ minWidth: '50%', opacity: 0.7, ...sx }}>
        <Box sx={{ textAlign: 'center', py: 3 }}>
          <Cloud sx={{ fontSize: 48, color: theme.palette.grey[400], mb: 2 }} />
          <p className="weather-error-message">
            {data?.message || 'Weather data unavailable'}
          </p>
          {data?.location && (
            <span className="weather-location-caption">
              Location: {data.location}
            </span>
          )}
        </Box>
      </GenericWidget>
    );
  }

  const { current, forecast, historical, units, location } = data;

  // Prepare chart data
  const tempChartData = historical?.dates ? historical.dates.map((date, idx) => ({
    date: formatChartDate(date),
    high: historical.maxTemps[idx],
    low: historical.minTemps[idx]
  })) : [];

  const windChartData = historical?.dates ? historical.dates.map((date, idx) => ({
    date: formatChartDate(date),
    max: historical.maxWindSpeeds[idx],
    avg: historical.avgWindSpeeds[idx]
  })) : [];

  return (
    <GenericWidget title={`Weather`} sx={{ minWidth: '50%', ...sx }}>
      {/* Current Weather Section */}
      <Box sx={{ mb: 3 }}>
        <h4>{location}</h4>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
          <Box sx={{ mr: 3 }}>
            {getWeatherIcon(current?.icon)}
          </Box>
          <Box sx={{ flexGrow: 1 }}>
            <span className="weather-temp-large">
              {Math.round(current?.temp || 0)}
            </span>
            <span className="weather-temp-unit">
              {units?.temperature}
            </span>
            <p className="weather-description-text">
              {current?.description}
            </p>
          </Box>
        </Box>

        <Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap', gap: 1 }}>
          <Chip
            icon={<Opacity />}
            label={`${current?.humidity}%`}
            size="small"
            variant="outlined"
            sx={{ borderColor: theme.palette.info.main }}
          />
          <Chip
            icon={<Air />}
            label={`${Math.round(current?.windSpeed || 0)} ${units?.windSpeed}`}
            size="small"
            variant="outlined"
            sx={{ borderColor: theme.palette.success.main }}
          />
          <Chip
            label={`Feels like ${Math.round(current?.apparentTemp || 0)}${units?.temperature}`}
            size="small"
            variant="outlined"
          />
        </Stack>
      </Box>

      <Divider sx={{ my: 2 }} />

      {/* 5-Day Forecast */}
      {forecast && forecast.length > 0 && (
        <Box sx={{ mb: 3 }}>
          <h6 className="weather-section-title">
            5-Day Forecast
          </h6>
          <Box sx={{ display: 'flex', gap: 1, overflowX: 'auto' }}>
            {forecast.map((day, index) => (
              <Paper
                key={index}
                elevation={1}
                sx={{
                  p: 1.5,
                  minWidth: 90,
                  textAlign: 'center',
                  bgcolor: theme.palette.mode === 'dark' 
                    ? 'rgba(255,255,255,0.05)' 
                    : 'rgba(0,0,0,0.02)',
                  borderRadius: 2
                }}
              >
                <span className="weather-forecast-day">
                  {index === 0 ? 'Today' : formatDate(day.date)}
                </span>
                {getForecastIcon(day.icon)}
                <p className="weather-forecast-temp-max">
                  {Math.round(day.maxTemp)}°
                </p>
                <span className="weather-forecast-temp-min">
                  {Math.round(day.minTemp)}°
                </span>
              </Paper>
            ))}
          </Box>
        </Box>
      )}

      <Divider sx={{ my: 2 }} />

      {/* Historical Temperature Chart */}
      {tempChartData.length > 0 && (
        <Box sx={{ mb: 3 }}>
          <h6 className="weather-section-title">
            7-Day Temperature History
          </h6>
          <LineChart
            height={250}
            series={[
              { 
                data: tempChartData.map(d => d.high), 
                label: 'High',
                color: theme.palette.error.main,
                showMark: false
              },
              { 
                data: tempChartData.map(d => d.low), 
                label: 'Low',
                color: theme.palette.info.main,
                showMark: false
              }
            ]}
            xAxis={[{ 
              scaleType: 'point', 
              data: tempChartData.map(d => d.date)
            }]}
            yAxis={[{
              label: `Temperature (${units?.temperature})`,
              labelStyle: { fontSize: 12 }
            }]}
            margin={{ top: 20, bottom: 100, left: 60, right: 30 }}
            sx={{
              '.MuiLineElement-root': {
                strokeWidth: 2
              },
              '.MuiMarkElement-root': {
                scale: '0.6'
              }
            }}
            slotProps={{
              legend: {
                direction: 'row',
                position: { vertical: 'top', horizontal: 'middle' },
                padding: 0
              }
            }}
          />
        </Box>
      )}

      <Divider sx={{ my: 2 }} />

      {/* Historical Wind Speed Chart */}
      {windChartData.length > 0 && (
        <Box>
          <h6 className="weather-section-title">
            7-Day Wind Speed History
          </h6>
          <LineChart
            height={250}
            series={[
              { 
                data: windChartData.map(d => d.max), 
                label: 'Max Wind',
                color: theme.palette.warning.main,
                showMark: false
              },
              { 
                data: windChartData.map(d => d.avg), 
                label: 'Avg Wind',
                color: theme.palette.success.main,
                showMark: false
              }
            ]}
            xAxis={[{ 
              scaleType: 'point', 
              data: windChartData.map(d => d.date)
            }]}
            yAxis={[{
              label: `Wind Speed (${units?.windSpeed})`,
              labelStyle: { fontSize: 12 }
            }]}
            margin={{ top: 20, bottom: 80, left: 60, right: 30 }}
            sx={{
              '.MuiLineElement-root': {
                strokeWidth: 2
              },
              '.MuiMarkElement-root': {
                scale: '0.6'
              }
            }}
            slotProps={{
              legend: {
                direction: 'row',
                position: { vertical: 'top', horizontal: 'middle' },
                padding: 0
              }
            }}
          />
        </Box>
      )}
    </GenericWidget>
  );
}

export default WeatherWidget;