import { useState, useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { FiTrendingUp, FiTrendingDown, FiStar } from 'react-icons/fi';
import { type Language } from '../translations';
import { AreaChart, Area, ResponsiveContainer, YAxis } from 'recharts';
import { useNavigate } from 'react-router-dom';
import { slugify } from '../utils/slugify';
import { useFavorites } from '../hooks/useFavorites';
import { Tooltip } from './Tooltip';
import { TbSwimming, TbSailboat, TbRipple } from 'react-icons/tb';

interface River {
  id: string;
  name: string;
  river: string;
  priority: boolean;
  level: number; // in cm for rivers
  capacity: number; // 0 for rivers
  storageDiff?: number;
  inflow: number;
  outflow: number; // current flow rate
  volume: number;
  maxVolume: number;
  navigationForbidden: boolean;
  sparkline: number[];
  type: 'lake' | 'river';
}

interface Props {
  language: Language;
  windUnit?: 'kmh' | 'ms';
}

const RiverCard = ({ river, language, isFav, onToggleFav }: { river: River, language: Language, isFav: boolean, onToggleFav: (id: string) => void }) => {
  const navigate = useNavigate();
  const chartData = river.sparkline.map((val, i) => ({ name: i, value: val }));
  
  const minVal = Math.min(...river.sparkline);
  const maxVal = Math.max(...river.sparkline);
  const diff = maxVal - minVal;
  const padding = diff === 0 ? 1 : diff * 0.1; // dynamic padding
  const yDomain = [minVal - padding, maxVal + padding];
  
  const firstVal = river.sparkline[0] || 0;
  const lastVal = river.sparkline[river.sparkline.length - 1] || 0;
  const trendDiff = lastVal - firstVal;
  
  // Dynamic color based on trend direction: stable=cyan, rising=green, falling=red
  let trendColor = 'var(--color-cyan)';
  if (trendDiff > 0.1) trendColor = 'var(--color-green)';
  else if (trendDiff < -0.1) trendColor = 'var(--color-red)';

  return (
    <div
      className="kpi-card priority-lake-card"
      onClick={() => navigate(`/${slugify(river.name)}`)}
      style={{ cursor: 'pointer', flex: 1, padding: '1.5rem', display: 'flex', flexDirection: 'column', gap: '1.5rem', position: 'relative' }}
    >
      {/* Star / Favorite button */}
      <button
        onClick={(e) => { e.stopPropagation(); onToggleFav(river.id); }}
        title={isFav ? (language === 'cs' ? 'Odepnout' : 'Unpin') : (language === 'cs' ? 'Připnout jako oblíbené' : 'Pin to favorites')}
        style={{
          position: 'absolute', top: '1rem', right: '1rem',
          background: 'none', border: 'none', cursor: 'pointer',
          color: isFav ? '#f59e0b' : 'var(--text-muted)',
          opacity: isFav ? 1 : 0.4,
          transition: 'color 0.2s, opacity 0.2s, transform 0.15s',
          padding: '4px',
          display: 'flex', alignItems: 'center',
          zIndex: 2,
        }}
        onMouseOver={(e) => { e.currentTarget.style.opacity = '1'; e.currentTarget.style.transform = 'scale(1.2)'; }}
        onMouseOut={(e) => { e.currentTarget.style.opacity = isFav ? '1' : '0.4'; e.currentTarget.style.transform = 'scale(1)'; }}
      >
        <FiStar size={18} fill={isFav ? '#f59e0b' : 'none'} />
      </button>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', paddingRight: '2rem' }}>
        <h3 style={{ fontSize: '1.25rem', fontWeight: 'bold', margin: 0 }}>
          {river.name} {river.river ? `- ${river.river}` : ''}
        </h3>
        <div style={{ display: 'flex', gap: '0.4rem', flexShrink: 0 }}>
          <Tooltip content={river.navigationForbidden ? (language === 'cs' ? 'Koupání zakázáno' : 'Swimming forbidden') : (language === 'cs' ? 'Koupání (bez omezení)' : 'Swimming allowed')}>
            <TbSwimming size={20} color={river.navigationForbidden ? 'var(--color-red)' : 'var(--color-green)'} style={{ opacity: river.navigationForbidden ? 0.5 : 0.8 }} />
          </Tooltip>
          <Tooltip content={river.navigationForbidden ? (language === 'cs' ? 'Plavba zakázána' : 'Navigation forbidden') : (language === 'cs' ? 'Plavba (i bezmotorová) povolena' : 'Navigation allowed')}>
            <TbSailboat size={20} color={river.navigationForbidden ? 'var(--color-red)' : 'var(--color-green)'} style={{ opacity: river.navigationForbidden ? 0.5 : 0.8 }} />
          </Tooltip>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginBottom: '1rem' }}>
        <div style={{
          width: '70px', height: '70px', borderRadius: '50%', 
          backgroundColor: 'rgba(6, 182, 212, 0.1)', 
          border: '2px dashed var(--color-cyan)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--color-cyan)', flexShrink: 0
        }}>
          <TbRipple size={36} />
        </div>
        <div>
          <div style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>
            {language === 'cs' ? 'Vodní stav' : 'Water level'}
          </div>
          <div style={{ fontSize: '2rem', fontWeight: 'bold', display: 'flex', alignItems: 'baseline', gap: '0.25rem', lineHeight: '1.1' }}>
            {river.level} <span style={{ fontSize: '1rem', fontWeight: 'normal', color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>cm</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginTop: '0.25rem' }}>
            <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)', whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: '0.25rem' }}>
              <span>{language === 'cs' ? 'Průtok:' : 'Flow:'}</span>
              <span style={{ color: 'var(--text-main)', fontWeight: 'bold' }}>{river.outflow} m³/s</span>
            </div>
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ flex: 1, height: '40px', marginRight: '2rem' }}>
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={chartData}>
              <defs>
                <linearGradient id={`colorSpark-${river.id}`} x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor={trendColor} stopOpacity={0.8} />
                  <stop offset="95%" stopColor={trendColor} stopOpacity={0} />
                </linearGradient>
              </defs>
              <YAxis domain={yDomain} hide />
              <Area type="monotone" dataKey="value" stroke={trendColor} fillOpacity={1} fill={`url(#colorSpark-${river.id})`} baseValue={yDomain[0]} />
            </AreaChart>
          </ResponsiveContainer>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.25rem', fontSize: '0.85rem' }}>
          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
            {trendDiff > 0.1 ? (
              <>
                <FiTrendingUp color="var(--color-green)" />
                <span style={{ color: 'var(--text-muted)' }}>{language === 'cs' ? 'Stoupá' : 'Rising'}</span>
              </>
            ) : trendDiff < -0.1 ? (
              <>
                <FiTrendingDown color="var(--color-red)" />
                <span style={{ color: 'var(--text-muted)' }}>{language === 'cs' ? 'Klesá' : 'Falling'}</span>
              </>
            ) : (
              <>
                <span style={{ color: 'var(--color-cyan)', fontWeight: 'bold' }}>~</span>
                <span style={{ color: 'var(--text-muted)' }}>{language === 'cs' ? 'Ustálený' : 'Stable'}</span>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export const RiversOverview = ({ language }: Props) => {
  const [rivers, setRivers] = useState<River[]>([]);
  const { isFavorite, toggleFavorite } = useFavorites();

  useEffect(() => {
    const loadData = () => {
      fetch(`/data/lakes_index.json?t=${Date.now()}`)
        .then(res => res.json())
        .then(data => {
          // Filter only rivers
          const filtered = data.filter((item: Partial<River>) => item.type === 'river');
          setRivers(filtered);
        })
        .catch(err => console.error(err));
    };

    loadData();
    const intervalId = setInterval(loadData, 60 * 1000); // Poll every 1 minute
    return () => clearInterval(intervalId);
  }, []);

  const favoriteRivers = rivers.filter(r => isFavorite(r.id));
  const activeRivers = rivers.filter(r => !isFavorite(r.id));
  activeRivers.sort((a, b) => a.name.localeCompare(b.name));

  const seoTitle = language === 'cs' ? 'Řeky a hlásné profily | Hladinátor' : 'Rivers and Flows | Hladinátor';
  const seoDesc = language === 'cs' 
    ? 'Sledujte aktuální vodní stavy (cm) a průtoky (m³/s) na klíčových vodočtech českých řek v reálném čase.'
    : 'Track current water levels (cm) and flow rates (m³/s) on key measuring stations of Czech rivers in real time.';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}>
      <Helmet>
        <title>{seoTitle}</title>
        <meta name="description" content={seoDesc} />
        <meta property="og:title" content={seoTitle} />
        <meta property="og:description" content={seoDesc} />
      </Helmet>
      
      <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
        <h1 style={{ fontSize: '1.75rem', fontWeight: 'bold', margin: '0', color: 'var(--text-main)' }}>
          {language === 'cs' ? 'Řeky a toky' : 'Rivers & Streams'} ({rivers.length})
        </h1>
        <p style={{ margin: 0, color: 'var(--text-muted)', fontSize: '0.95rem', lineHeight: '1.5' }}>
          {seoDesc}
        </p>
      </div>

      {/* Favorites section */}
      {favoriteRivers.length > 0 && (
        <section>
          <h2 style={{ fontSize: '1.1rem', fontWeight: 'bold', marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
            <FiStar size={16} fill="#f59e0b" color="#f59e0b" /> {language === 'cs' ? 'Oblíbené' : 'Favorites'} ({favoriteRivers.length})
          </h2>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))',
            gap: '1.5rem'
          }}>
            {favoriteRivers.map(river => (
              <RiverCard key={river.id} river={river} language={language} isFav={true} onToggleFav={toggleFavorite} />
            ))}
          </div>
        </section>
      )}

      {/* All Rivers section */}
      {activeRivers.length > 0 && (
        <section>
          <h2 style={{ fontSize: '1.1rem', fontWeight: 'bold', marginBottom: '1rem' }}>
            {language === 'cs' ? 'Sledované profily' : 'Monitored Profiles'}
          </h2>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))',
            gap: '1.5rem'
          }}>
            {activeRivers.map(river => (
              <RiverCard key={river.id} river={river} language={language} isFav={false} onToggleFav={toggleFavorite} />
            ))}
          </div>
        </section>
      )}
    </div>
  );
};
