import { useState, useEffect } from 'react';
import { ComposedChart, Line, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { FiWind } from 'react-icons/fi';
import { type Language } from '../translations';

interface WindChartProps {
  lat: number;
  lng: number;
  language: Language;
  timeRange?: '24h' | '7d' | '30d' | '1y' | 'all';
  windUnit?: 'kmh' | 'ms';
}

interface WindDataPoint {
  time: string;
  speed: number;
  gusts: number;
  dir: number;
  dirStr: string;
}

const getCompassDirection = (degrees: number, language: 'cs' | 'en') => {
  const directionsEn = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
  const directionsCs = ['S', 'SV', 'V', 'JV', 'J', 'JZ', 'Z', 'SZ'];
  const directions = language === 'cs' ? directionsCs : directionsEn;
  const index = Math.round(((degrees %= 360) < 0 ? degrees + 360 : degrees) / 45) % 8;
  return directions[index];
};

interface CustomWindTooltipProps {
  active?: boolean;
  payload?: { payload: WindDataPoint, value: number, name: string }[];
  label?: string;
  language: 'cs' | 'en';
  windUnit?: 'kmh' | 'ms';
  coordinate?: { x: number; y: number };
  viewBox?: { width: number; height: number };
}

const CustomWindTooltip = ({ active, payload, label, language, windUnit = 'kmh', coordinate, viewBox }: CustomWindTooltipProps) => {
  if (active && payload && payload.length) {
    const isLeft = coordinate && viewBox && coordinate.x > viewBox.width / 2;
    const tooltipClass = `chart-tooltip ${isLeft ? 'tooltip-left' : 'tooltip-right'}`;
    const data = payload[0].payload;
    const date = new Date(label);
    const dateStr = date.toLocaleDateString(language === 'cs' ? 'cs-CZ' : 'en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' });
    const timeStr = date.toLocaleTimeString(language === 'cs' ? 'cs-CZ' : 'en-GB', { hour: '2-digit', minute: '2-digit' });
    
    return (
      <div className={tooltipClass} style={{ backgroundColor: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: '8px', padding: '8px 10px', boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.5)', color: 'var(--text-main)', fontSize: '0.8rem', zIndex: 100 }}>
        <div style={{ fontWeight: 'bold', marginBottom: '6px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '3px', fontSize: '0.85rem' }}>
          {dateStr} {timeStr}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            <span style={{ color: 'var(--color-cyan)', fontSize: '1rem' }}>●</span>
            <span>{language === 'cs' ? 'Rychlost větru' : 'Wind Speed'}: <strong>{data.speed} {windUnit === 'kmh' ? 'km/h' : 'm/s'}</strong></span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            <span style={{ color: 'var(--color-purple)', fontSize: '1rem' }}>●</span>
            <span>{language === 'cs' ? 'Nárazy větru' : 'Wind Gusts'}: <strong>{data.gusts} {windUnit === 'kmh' ? 'km/h' : 'm/s'}</strong></span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginTop: '2px', color: 'var(--text-muted)' }}>
            <FiWind />
            <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
              {language === 'cs' ? 'Směr' : 'Direction'}: <strong>{data.dirStr} ({data.dir}°)</strong>
              <svg 
                width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
                style={{ transform: `rotate(${data.dir + 180}deg)` }}
              >
                <line x1="12" y1="19" x2="12" y2="5"></line>
                <polyline points="5 12 12 5 19 12"></polyline>
              </svg>
            </span>
          </div>
        </div>
      </div>
    );
  }
  return null;
};

const CustomWindDot = (props: { cx?: number; cy?: number; payload?: WindDataPoint }) => {
  const { cx, cy, payload } = props;
  
  if (!cx || !cy || payload.dir === undefined) return null;

  return (
    <g transform={`translate(${cx},${cy}) rotate(${payload.dir + 180}) scale(1.5)`}>
      <path 
        d="M0,-6 L-4,4 L0,2 L4,4 Z" 
        fill="var(--color-cyan)" 
        stroke="#1e293b"
        strokeWidth={1}
      />
    </g>
  );
};

export const WindChart = ({ lat, lng, language, timeRange = '24h', windUnit = 'kmh' }: WindChartProps) => {
  const [data, setData] = useState<WindDataPoint[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentSpeed, setCurrentSpeed] = useState(0);
  const [currentDir, setCurrentDir] = useState(0);
  const [maxGust, setMaxGust] = useState(0);
  const [isMobile, setIsMobile] = useState(false);
  const [tooltipY, setTooltipY] = useState<number | undefined>(undefined);

  useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth <= 768);
    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  useEffect(() => {
    const fetchWind = async () => {
      try {
        setLoading(true);
        let url = '';
        let isDaily = false;
        
        if (timeRange === '1y' || timeRange === 'all') {
          isDaily = true;
          const end = new Date();
          end.setDate(end.getDate() - 1);
          const endStr = end.toISOString().split('T')[0];
          
          const start = new Date();
          if (timeRange === '1y') {
            start.setDate(start.getDate() - 365);
          } else {
            start.setFullYear(2020);
          }
          const startStr = start.toISOString().split('T')[0];
          
          url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${startStr}&end_date=${endStr}&daily=wind_speed_10m_max,wind_gusts_10m_max,wind_direction_10m_dominant&wind_speed_unit=${windUnit}&timezone=auto`;
        } else {
          let pastDays = 7;
          if (timeRange === '24h') pastDays = 1;
          if (timeRange === '30d') pastDays = 30;
          url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&hourly=wind_speed_10m,wind_gusts_10m,wind_direction_10m&past_days=${pastDays}&forecast_days=1&wind_speed_unit=${windUnit}&timezone=auto`;
        }

        const res = await fetch(url);
        if (!res.ok) throw new Error('Failed to fetch wind data');
        const json = await res.json();
        
        const times = isDaily ? json.daily.time : json.hourly.time;
        const speeds = isDaily ? json.daily.wind_speed_10m_max : json.hourly.wind_speed_10m;
        const gusts = isDaily ? json.daily.wind_gusts_10m_max : json.hourly.wind_gusts_10m;
        const dirs = isDaily ? json.daily.wind_direction_10m_dominant : json.hourly.wind_direction_10m;
        
        const chartData: WindDataPoint[] = [];
        let maxG = 0;
        
        const now = new Date();
        let closestIdx = 0;
        let minDiff = Infinity;
        
        for (let i = 0; i < times.length; i++) {
          const t = new Date(times[i]);
          const diff = Math.abs(t.getTime() - now.getTime());
          if (diff < minDiff) {
            minDiff = diff;
            closestIdx = i;
          }
          
          if (t.getTime() <= now.getTime() || isDaily) {
            if (gusts[i] > maxG) maxG = gusts[i];
            chartData.push({
              time: times[i],
              speed: speeds[i] || 0,
              gusts: gusts[i] || 0,
              dir: dirs[i] || 0,
              dirStr: getCompassDirection(dirs[i] || 0, language)
            });
          }
        }
        
        let downsampleFactor = 1;
        if (timeRange === '7d') downsampleFactor = 3;
        if (timeRange === '30d') downsampleFactor = 12;
        if (timeRange === '1y') downsampleFactor = 3;
        if (timeRange === 'all') downsampleFactor = 14;
        
        const downsampled = chartData.filter((_, i) => i % downsampleFactor === 0 || i === chartData.length - 1);
        
        setData(downsampled);
        setMaxGust(maxG);
        setCurrentSpeed(speeds[closestIdx] || speeds[speeds.length - 1] || 0);
        setCurrentDir(dirs[closestIdx] || dirs[dirs.length - 1] || 0);
        
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    };
    
    if (lat && lng) {
      fetchWind();
    }
  }, [lat, lng, language, timeRange, windUnit]);

  if (loading) {
    return (
      <div style={{ marginTop: '2rem', display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '200px', color: 'var(--text-muted)' }}>
        {language === 'cs' ? 'Načítám data o větru...' : 'Loading wind data...'}
      </div>
    );
  }

  if (data.length === 0) return null;

  return (
    <div style={{ marginTop: '1.5rem', paddingTop: '0.5rem', display: 'flex', flexDirection: 'column', gap: '0' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: '1rem', padding: isMobile ? '0 0.75rem' : '0', marginBottom: '0.25rem' }}>
        <h3 style={{ margin: 0, fontSize: '1.1rem', color: 'var(--text-main)', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
          <FiWind style={{ color: 'var(--color-cyan)' }} />
          {language === 'cs' ? `Aktivita větru (${timeRange === '1y' || timeRange === 'all' ? 'denní maxima' : timeRange})` : `Wind Activity (${timeRange === '1y' || timeRange === 'all' ? 'daily max' : timeRange})`}
        </h3>
        
        <div style={{ 
          display: 'flex', 
          gap: isMobile ? '0' : '1.5rem', 
          justifyContent: isMobile ? 'space-around' : 'flex-end', 
          width: isMobile ? '100%' : 'auto',
          marginTop: isMobile ? '0.5rem' : '0'
        }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>{language === 'cs' ? 'Aktuální rychlost' : 'Current Speed'}</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}>
              <span style={{ fontSize: '1.5rem', fontWeight: 'bold', color: 'var(--text-main)' }}>{currentSpeed.toFixed(1)}</span>
              <span style={{ fontSize: '0.9rem', color: 'var(--color-cyan)' }}>{windUnit === 'kmh' ? 'km/h' : 'm/s'}</span>
              <svg 
                width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
                style={{ color: 'var(--color-cyan)', marginLeft: '2px', transform: `rotate(${currentDir + 180}deg)`, transition: 'transform 0.3s ease' }}
              >
                <line x1="12" y1="19" x2="12" y2="5"></line>
                <polyline points="5 12 12 5 19 12"></polyline>
              </svg>
            </div>
          </div>
          
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>{language === 'cs' ? 'Max. nárazy' : 'Peak Gusts'}</span>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: '0.25rem' }}>
              <span style={{ fontSize: '1.5rem', fontWeight: 'bold', color: 'var(--text-main)' }}>{maxGust.toFixed(1)}</span>
              <span style={{ fontSize: '0.9rem', color: 'var(--color-purple)' }}>{windUnit === 'kmh' ? 'km/h' : 'm/s'}</span>
            </div>
          </div>
        </div>
      </div>
      
      <div style={{ flex: 1, minHeight: '280px', width: '100%', marginTop: '0' }}>
        <ResponsiveContainer width="100%" height="100%">
          <ComposedChart 
            data={data} 
            margin={isMobile ? { top: 5, right: 5, left: 5, bottom: 0 } : { top: 5, right: 0, left: -20, bottom: 0 }}
            onMouseMove={(state: { chartY?: number } | null | undefined) => {
              if (state && state.chartY !== undefined) {
                const isBottomHalf = state.chartY > 140;
                const targetY = isBottomHalf ? 5 : 160;
                if (tooltipY !== targetY) setTooltipY(targetY);
              }
            }}
            onMouseLeave={() => setTooltipY(undefined)}
          >
            <defs>
              <linearGradient id="colorWind" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="var(--color-cyan)" stopOpacity={0.4}/>
                <stop offset="95%" stopColor="var(--color-cyan)" stopOpacity={0}/>
              </linearGradient>
            </defs>
            <XAxis 
              dataKey="time" 
              stroke="var(--text-muted)" 
              tick={{fill: 'var(--text-muted)', fontSize: isMobile ? 10 : 11}} 
              minTickGap={60} 
              tickFormatter={(v) => {
                const d = new Date(v);
                return `${d.getDate()}.${d.getMonth()+1}.`;
              }} 
            />
            <YAxis 
              stroke="var(--text-muted)" 
              tick={{fill: 'var(--text-muted)', fontSize: isMobile ? 10 : 11}} 
              width={isMobile ? 35 : 60}
              tickFormatter={(v) => v.toFixed(1)}
            />
            <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" vertical={false} />
            <Tooltip 
              content={<CustomWindTooltip language={language} windUnit={windUnit} />} 
              position={tooltipY !== undefined ? { y: tooltipY } : undefined}
            />
            
            <Area 
              type="monotone" 
              dataKey="speed" 
              stroke="var(--color-cyan)" 
              strokeWidth={2} 
              fillOpacity={1} 
              fill="url(#colorWind)" 
              isAnimationActive={true} 
              dot={(props: any) => {
                const step = Math.max(1, Math.floor(data.length / (isMobile ? 15 : 30)));
                if (props.index % step !== 0 && props.index !== data.length - 1) return null;
                return <CustomWindDot key={props.index} {...props} />;
              }}
              activeDot={{ r: 6, fill: 'var(--color-cyan)', stroke: '#1e293b', strokeWidth: 2 }}
            />
            <Line 
              type="monotone" 
              dataKey="gusts" 
              stroke="var(--color-purple)" 
              strokeWidth={2} 
              strokeDasharray="5 5" 
              dot={false} 
              isAnimationActive={true} 
            />
          </ComposedChart>
        </ResponsiveContainer>
      </div>
      
      <div style={{ display: 'flex', justifyContent: 'center', gap: '1.5rem', fontSize: '0.85rem', color: 'var(--text-muted)', marginTop: '0.5rem', padding: isMobile ? '0 0.75rem' : '0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
          <span style={{ display: 'inline-block', width: '12px', height: '3px', backgroundColor: 'var(--color-cyan)' }}></span>
          <span>{language === 'cs' ? 'Rychlost větru' : 'Wind Speed'}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
          <span style={{ display: 'inline-block', width: '12px', height: '3px', borderTop: '2px dashed var(--color-purple)' }}></span>
          <span>{language === 'cs' ? 'Nárazy větru' : 'Wind Gusts'}</span>
        </div>
      </div>
    </div>
  );
};
