import { Check, TrendingUp, X } from 'lucide-react';
import { Match } from '../api/client';
import styles from './MatchCard.module.css';

interface Props {
  match: Match;
  onTip: () => void;
}

const STATUS_LABELS: Record<string, string> = {
  SCHEDULED: 'Geplant',
  TIMED: 'Terminiert',
  IN_PLAY: 'Live',
  PAUSED: 'Pause',
  FINISHED: 'Beendet',
  POSTPONED: 'Verschoben',
  CANCELLED: 'Abgesagt',
};

function formatKickoff(utcDate: string): string {
  return new Date(utcDate).toLocaleString('de-DE', {
    hour: '2-digit', minute: '2-digit', timeZone: 'Europe/Berlin',
  }) + ' Uhr';
}

function CountdownBadge({ minutes }: { minutes: number }) {
  if (minutes <= 0) return null;
  if (minutes < 60) return <span className={styles.badgeUrgent}>⚡ in {minutes} Min.</span>;
  const h = Math.floor(minutes / 60);
  const m = minutes % 60;
  if (h < 24) return <span className={styles.badge}>in {h}h{m > 0 ? ` ${m}m` : ''}</span>;
  const d = Math.floor(h / 24);
  return <span className={styles.badge}>in {d} Tag{d > 1 ? 'en' : ''}</span>;
}

function FlagBox({ crest, name }: { crest: string | null; name: string }) {
  return (
    <div className={styles.flagBox}>
      {crest
        ? <img className={styles.crest} src={crest} alt={name} />
        : <span style={{ fontSize: 18 }}>🏳️</span>
      }
    </div>
  );
}

export default function MatchCard({ match, onTip }: Props) {
  const isFinished = match.status === 'FINISHED';
  const isLive = match.status === 'IN_PLAY' || match.status === 'PAUSED';
  const hasTip = !!match.userTip;
  const points = match.userTip?.points ?? null;
  const resultClass =
    points === 3 ? styles.exact :
    points === 1 ? styles.tendency :
    (points === 0 && isFinished) ? styles.wrong : '';

  const glowClass =
    isFinished && points === 3 ? styles.glowExact :
    isFinished && points === 1 ? styles.glowTendency :
    isFinished && points === 0 ? styles.glowWrong : '';

  return (
    <div className={`card ${styles.card} ${isLive ? styles.live : ''} ${glowClass}`}>

      {/* Top row: Status / Kickoff / Badges */}
      <div className={styles.topRow}>
        <span className={`${styles.status} ${isLive ? styles.statusLive : ''}`}>
          {isLive && '● '}{STATUS_LABELS[match.status] ?? match.status}
        </span>
        {match.group && (
          <span className={styles.group}>
            {match.group.replace('GROUP_', 'Gruppe ')}
          </span>
        )}
        {match.tippable && <CountdownBadge minutes={match.minutesUntilKickoff} />}
      </div>

      {/* Teams + Score */}
      <div className={styles.matchRow}>
        {/* Home */}
        <div className={styles.teamHome}>
          <span className={styles.teamName}>{match.homeTeam.name}</span>
          <FlagBox crest={match.homeTeam.crest} name={match.homeTeam.name} />
        </div>

        {/* Score / Kickoff time */}
        <div className={styles.scoreBox}>
          {isFinished || isLive ? (
            <span className={styles.score}>
              {match.score.home ?? '–'}&nbsp;:&nbsp;{match.score.away ?? '–'}
            </span>
          ) : (
            <div className={styles.kickoffCenter}>
              <span className={styles.kickoffCenterTime}>{formatKickoff(match.utcDate)}</span>
            </div>
          )}
        </div>

        {/* Away */}
        <div className={styles.teamAway}>
          <FlagBox crest={match.awayTeam.crest} name={match.awayTeam.name} />
          <span className={styles.teamName}>{match.awayTeam.name}</span>
        </div>
      </div>

      {/* Tipp area — wird zum farbigen Banner wenn Punkte ausgewertet */}
      <div className={`${styles.tipRow} ${hasTip && points !== null ? `${styles.resultBanner} ${resultClass}` : ''}`}>
        {hasTip ? (
          points !== null ? (
            /* ── Auswertungs-Banner ── */
            <div className={styles.tipDisplay}>
              {/* Links: Icon + Ergebnis-Label nebeneinander, zentriert zur Tippbox */}
              <div className={`${styles.tipLeft} ${styles.bannerLeft}`}>
                <span className={styles.resultIcon}>
                  {points === 3 ? <Check size={14} strokeWidth={3} /> :
                   points === 1 ? <TrendingUp size={14} strokeWidth={2.5} /> :
                   <X size={14} strokeWidth={3} />}
                </span>
                <span className={styles.resultLabel}>
                  {points === 3 ? 'Exakt' : points === 1 ? 'Tendenz' : 'Falsch'}
                </span>
              </div>

              {/* Mitte: nur Score, kein Label */}
              <div className={styles.tipCenter}>
                <span className={styles.tipScoreBanner}>
                  {match.userTip!.home} : {match.userTip!.away}
                </span>
              </div>

              {/* Rechts: Punkte */}
              <div className={styles.tipRight}>
                <span className={styles.resultPoints}>
                  {points === 0 ? '0 Pkt.' : `+${points} Pkt.`}
                </span>
              </div>
            </div>
          ) : (
            /* ── Tipp vorhanden, noch nicht ausgewertet ── */
            <div className={styles.tipDisplay}>
              <div className={styles.tipLeft}>
                {match.tippable && (
                  <button className={styles.editBtn} onClick={onTip}>Ändern</button>
                )}
              </div>
              <div className={styles.tipCenter}>
                {/* Label nur zeigen wenn kein Ändern-Button da ist, sonst fluchtet der Button nicht */}
                {!match.tippable && <span className={styles.tipLabel}>DEIN TIPP</span>}
                <span className={styles.tipScore}>
                  {match.userTip!.home} : {match.userTip!.away}
                </span>
              </div>
              <div className={styles.tipRight} />
            </div>
          )
        ) : match.tippable ? (
          <button className={`btn-primary ${styles.tipBtn}`} onClick={onTip}>
            Tipp abgeben
          </button>
        ) : (
          <span className={styles.noTip}>Kein Tipp abgegeben</span>
        )}
      </div>
    </div>
  );
}
