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

interface Lake {
  id: string;
  name: string;
  river: string;
  priority: boolean;
  level: number;
  capacity: number;
  storageDiff?: number;
  inflow: number;
  outflow: number;
  volume: number;
  maxVolume: number;
  navigationForbidden: boolean;
  sparkline: number[];
}

interface Props {
  language: Language;
}

const FavoritesOverview = ({ language }: Props) => {
  const [lakes, setLakes] = useState<Lake[]>([]);
  const { isFavorite, toggleFavorite } = useFavorites();
  const navigate = useNavigate();

  useEffect(() => {
    fetch(`/data/lakes_index.json?t=${Date.now()}`)
      .then(res => res.json())
      .then(data => setLakes(data))
      .catch(err => console.error(err));
  }, []);

  const favoriteLakes = lakes.filter(l => isFavorite(l.id));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}>
      <Helmet>
        <title>{t[language].seo.favoritesTitle}</title>
        <meta name="description" content={t[language].seo.favoritesDesc} />
        <meta property="og:title" content={t[language].seo.favoritesTitle} />
        <meta property="og:description" content={t[language].seo.favoritesDesc} />
      </Helmet>
      <div>
        <h1 style={{ fontSize: '1.75rem', fontWeight: 'bold', margin: '0 0 0.5rem 0', display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
          <FiStar size={24} fill="#f59e0b" color="#f59e0b" />
          {language === 'cs' ? 'Oblíbená' : 'Favourites'}
        </h1>
        <p style={{ margin: 0, color: 'var(--text-muted)', fontSize: '0.9rem' }}>
          {language === 'cs'
            ? 'Jezera připnutá v přehledu. Připnout nebo odepnout lze ikonou hvězdičky.'
            : 'Lakes you pinned in the overview. Use the star icon to pin or unpin.'}
        </p>
      </div>

      {favoriteLakes.length === 0 ? (
        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          gap: '1rem', padding: '4rem 2rem', color: 'var(--text-muted)', textAlign: 'center'
        }}>
          <FiStar size={48} strokeWidth={1.2} color="var(--text-muted)" />
          <p style={{ margin: 0, fontSize: '1.1rem' }}>
            {language === 'cs' ? 'Zatím žádná oblíbená jezera.' : 'No favourites yet.'}
          </p>
          <p style={{ margin: 0, fontSize: '0.85rem' }}>
            {language === 'cs'
              ? 'Přejdi na Jezera a nádrže a klikni na ⭐ u jezera, které tě zajímá.'
              : 'Go to Lakes & Reservoirs and click the ⭐ on any lake to pin it here.'}
          </p>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: '1.5rem' }}>
          {favoriteLakes.map(lake => {
            const chartData = lake.sparkline.map((val, i) => ({ name: i, value: val }));
            
            const minVal = Math.min(...lake.sparkline);
            const maxVal = Math.max(...lake.sparkline);
            const diff = maxVal - minVal;
            const padding = diff === 0 ? 0.1 : diff * 0.1;
            const yDomain = [minVal - padding, maxVal + padding];
            
            const firstVal = lake.sparkline[0] || 0;
            const lastVal = lake.sparkline[lake.sparkline.length - 1] || 0;
            const trendDiff = lastVal - firstVal;
            
            let trendColor = 'var(--color-cyan)';
            if (trendDiff > 0.01) trendColor = 'var(--color-green)';
            else if (trendDiff < -0.01) trendColor = 'var(--color-red)';
            
            return (
              <div
                key={lake.id}
                className="kpi-card priority-lake-card"
                onClick={() => navigate(`/${slugify(lake.name)}`)}
                style={{ cursor: 'pointer', padding: '1.5rem', display: 'flex', flexDirection: 'column', gap: '1.5rem', position: 'relative' }}
              >
                {/* Unpin button */}
                <button
                  onClick={(e) => { e.stopPropagation(); toggleFavorite(lake.id); }}
                  title={language === 'cs' ? 'Odepnout' : 'Unpin'}
                  style={{
                    position: 'absolute', top: '1rem', right: '1rem',
                    background: 'none', border: 'none', cursor: 'pointer',
                    color: '#f59e0b', transition: 'transform 0.15s',
                    padding: '4px', display: 'flex', alignItems: 'center', zIndex: 2,
                  }}
                  onMouseOver={(e) => { e.currentTarget.style.transform = 'scale(1.2)'; }}
                  onMouseOut={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
                >
                  <FiStar size={18} fill="#f59e0b" />
                </button>

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

                <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginBottom: '1rem' }}>
                  <CircularProgress value={lake.capacity} size={70} strokeWidth={6} />
                  <div>
                    <div style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>{t[language].kpi.level}</div>
                    <div style={{ fontSize: '2rem', fontWeight: 'bold', display: 'flex', alignItems: 'baseline', gap: '0.25rem', lineHeight: '1.1' }}>
                      {lake.level} <span style={{ fontSize: '1rem', fontWeight: 'normal', color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>m n.m.</span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginTop: '0.25rem' }}>
                      {lake.storageDiff !== undefined && (
                        <div style={{ fontSize: '1rem', color: lake.storageDiff >= 0 ? 'var(--color-green)' : 'var(--color-red)', fontWeight: 'bold', whiteSpace: 'nowrap' }}>
                          {lake.storageDiff > 0 ? '+' : ''}{lake.storageDiff.toFixed(2)} m
                        </div>
                      )}
                      {lake.maxVolume > 0 && (
                        <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>
                          {lake.volume.toFixed(1)} / {lake.maxVolume.toFixed(1)} mil. m³
                        </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={`colorSparkFav-${lake.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(#colorSparkFav-${lake.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' }}>
                      <FiTrendingUp color="var(--color-green)" />
                      <span style={{ color: 'var(--text-muted)' }}>{t[language].kpi.inflow} <span style={{ color: 'var(--color-green)' }}>{lake.inflow} m³/s</span></span>
                    </div>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                      <FiTrendingDown color="var(--color-red)" />
                      <span style={{ color: 'var(--text-muted)' }}>{t[language].kpi.outflow} <span style={{ color: 'var(--color-red)' }}>{lake.outflow} m³/s</span></span>
                    </div>
                  </div>
                </div>

              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default FavoritesOverview;
