import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api, DashboardData } from '../api/client';
import styles from './DashboardPage.module.css';

interface Props {
  devUser?: number;
}

function formatStreak(streak: number): string {
  if (streak >= 20) return `⚡${streak}`;
  if (streak >= 10) return `🔥🔥${streak}`;
  if (streak >= 3) return `🔥${streak}`;
  if (streak > 0) return String(streak);
  return '0';
}

function formatCountdown(minutes: number): string {
  if (minutes < 60) return `in ${minutes} Min`;
  if (minutes < 60 * 24) return `in ${Math.floor(minutes / 60)}h`;
  return `in ${Math.floor(minutes / (60 * 24))} Tagen`;
}

export default function DashboardPage(_props: Props) {
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    setLoading(true);
    setError(false);
    api.getDashboard()
      .then(d => { setData(d); setLoading(false); })
      .catch(() => { setError(true); setLoading(false); });
  }, []);

  if (loading) return <div className={styles.loading}>Laden...</div>;
  if (error || !data) return <div className={styles.error}>Dashboard konnte nicht geladen werden.</div>;

  const { hero, stats, nudges } = data;

  return (
    <div className={styles.dashboard}>
      {/* Hero Card */}
      <div className={styles.hero} onClick={() => navigate('/spiele')}>
        <div className={styles.heroLabel}>
          <span>Nächstes Spiel</span>
          {hero && (
            <span className={styles.heroCountdown}>
              {formatCountdown(hero.match.minutesUntilKickoff)}
            </span>
          )}
        </div>

        {hero ? (
          <>
            <div className={styles.heroTeams}>
              <div className={styles.heroTeam}>
                {hero.match.homeTeam.crest ? (
                  <img
                    src={hero.match.homeTeam.crest}
                    alt={hero.match.homeTeam.name}
                    className={styles.heroCrest}
                  />
                ) : (
                  <div className={styles.heroCrest} />
                )}
                <span>{hero.match.homeTeam.shortName}</span>
              </div>
              <span className={styles.heroVs}>vs</span>
              <div className={styles.heroTeam}>
                {hero.match.awayTeam.crest ? (
                  <img
                    src={hero.match.awayTeam.crest}
                    alt={hero.match.awayTeam.name}
                    className={styles.heroCrest}
                  />
                ) : (
                  <div className={styles.heroCrest} />
                )}
                <span>{hero.match.awayTeam.shortName}</span>
              </div>
            </div>

            {hero.userTip ? (
              <div className={styles.heroTip}>
                Dein Tipp: {hero.userTip.home}:{hero.userTip.away} ✓
              </div>
            ) : hero.tippable ? (
              <button
                className={styles.heroTipBtn}
                onClick={e => { e.stopPropagation(); navigate('/spiele'); }}
              >
                Jetzt tippen
              </button>
            ) : null}
          </>
        ) : (
          <p style={{ textAlign: 'center', color: 'var(--text-muted)', margin: '16px 0' }}>
            Keine anstehenden Spiele
          </p>
        )}
      </div>

      {/* Stats Row */}
      <div className={styles.statsRow}>
        <div className={styles.statTile}>
          <span className={styles.statValue}>
            {stats.rank !== null ? stats.rank : '—'}
          </span>
          <span className={styles.statLabel}>Dein Rang</span>
        </div>
        <div className={styles.statTile}>
          <span className={styles.statValue}>{stats.totalPoints}</span>
          <span className={styles.statLabel}>Punkte</span>
        </div>
        <div className={styles.statTile}>
          <span className={styles.statValue}>{formatStreak(stats.streak)}</span>
          <span className={styles.statLabel}>Streak</span>
        </div>
      </div>

      {/* Nudges */}
      {nudges.length > 0 && (
        <div className={styles.nudges}>
          {nudges.map((nudge, i) => (
            <div
              key={i}
              className={styles.nudge}
              onClick={() => {
                if (nudge.type === 'untipped') navigate('/spiele');
                else if (nudge.type === 'leader') navigate('/rangliste');
              }}
            >
              {nudge.text}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
