import { useState, useEffect } from 'react';
import { api, UserStats, MyTip } from '../api/client';
import StatsRing from '../components/StatsRing';
import styles from './ProfilePage.module.css';

function initials(name: string) {
  return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
}

function mostCommonTip(tips: MyTip[]): string {
  const counts: Record<string, number> = {};
  for (const t of tips) {
    const key = `${t.tip_home}:${t.tip_away}`;
    counts[key] = (counts[key] ?? 0) + 1;
  }
  let best = '';
  let max = 0;
  for (const [key, count] of Object.entries(counts)) {
    if (count > max) { max = count; best = key; }
  }
  return best ? `${best} (${max}x getippt)` : '—';
}

function homeWinPct(tips: MyTip[]): number {
  if (!tips.length) return 0;
  const homeWins = tips.filter(t => t.tip_home > t.tip_away).length;
  return Math.round((homeWins / tips.length) * 100);
}

export default function ProfilePage() {
  const [stats, setStats]           = useState<UserStats | null>(null);
  const [tips, setTips]             = useState<MyTip[]>([]);
  const [loading, setLoading]       = useState(true);
  const [teamEdit, setTeamEdit]     = useState(false);
  const [teamValue, setTeamValue]   = useState('');
  const [teamSaving, setTeamSaving] = useState(false);
  const [teamMsg, setTeamMsg]       = useState<{ ok: boolean; text: string } | null>(null);

  useEffect(() => {
    Promise.all([
      api.getMyStats(),
      api.getMyTips(),
    ]).then(([s, t]) => {
      setStats(s);
      setTeamValue(s.team ?? '');
      setTips(t.tips);
    }).finally(() => setLoading(false));
  }, []);

  const saveTeam = async () => {
    if (!teamValue.trim()) return;
    setTeamSaving(true);
    setTeamMsg(null);
    try {
      const res = await api.updateTeam(teamValue);
      setStats(prev => prev ? { ...prev, team: res.team } : prev);
      setTeamValue(res.team);
      setTeamEdit(false);
      setTeamMsg({ ok: true, text: 'Team gespeichert' });
    } catch (e) {
      setTeamMsg({ ok: false, text: (e as Error).message });
    } finally {
      setTeamSaving(false);
    }
  };

  if (loading) return <div className={styles.loading}><div className={styles.spinner} /></div>;
  if (!stats)  return <div className={styles.empty}>Profil nicht verfügbar.</div>;

  const evaluatedTips = tips.filter(t => t.points !== null);
  const recentTips    = evaluatedTips.slice(0, 10);

  const favTip        = mostCommonTip(tips);
  const homePct       = homeWinPct(tips);

  function pointBadgeClass(points: number | null) {
    if (points === null) return '';
    if (points >= 3) return styles.badgeExact;
    if (points >= 1) return styles.badgeTendency;
    return styles.badgeWrong;
  }

  function pointLabel(points: number | null) {
    if (points === null) return '';
    if (points >= 3) return `${points} Pkt ✓✓`;
    if (points >= 1) return `${points} Pkt ✓`;
    return `${points} Pkt ✗`;
  }

  return (
    <div className={styles.page}>

      {/* Header card */}
      <div className={`card ${styles.heroCard}`}>
        <div className={styles.avatar}>{initials(stats.fullName)}</div>
        <div className={styles.heroInfo}>
          <h1 className={`font-display ${styles.name}`}>{stats.fullName}</h1>
          {stats.rank && <div className={styles.rankBadge}>🏆 Platz {stats.rank}</div>}

          {/* Team field */}
          <div className={styles.teamRow}>
            {teamEdit ? (
              <div className={styles.teamEditRow}>
                <input
                  className={styles.teamInput}
                  value={teamValue}
                  onChange={e => setTeamValue(e.target.value)}
                  placeholder="z. B. Vertrieb Süd"
                  maxLength={80}
                  autoFocus
                  onKeyDown={e => {
                    if (e.key === 'Enter') saveTeam();
                    if (e.key === 'Escape') setTeamEdit(false);
                  }}
                />
                <button className={styles.teamSaveBtn} onClick={saveTeam} disabled={teamSaving}>
                  {teamSaving ? <span className={styles.spinnerSm} /> : '✓'}
                </button>
                <button
                  className={styles.teamCancelBtn}
                  onClick={() => { setTeamEdit(false); setTeamValue(stats.team ?? ''); }}
                >
                  ✕
                </button>
              </div>
            ) : (
              <button className={styles.teamBtn} onClick={() => setTeamEdit(true)}>
                {stats.team
                  ? <><span className={styles.teamName}>{stats.team}</span><span className={styles.teamEditHint}>bearbeiten</span></>
                  : <span className={styles.teamPlaceholder}>+ Team hinzufügen</span>
                }
              </button>
            )}
          </div>
          {teamMsg && (
            <div className={`${styles.teamMsg} ${teamMsg.ok ? styles.teamMsgOk : styles.teamMsgErr}`}>
              {teamMsg.text}
            </div>
          )}
        </div>
      </div>

      {/* Stats donut ring */}
      <div className={`card ${styles.ringCard}`}>
        <h2 className={styles.sectionTitle}>Tipp-Statistik</h2>
        <StatsRing
          exact={stats.exactCount}
          tendency={stats.tendencyCount}
          wrong={stats.wrongCount}
          total={stats.totalPoints}
        />
        {stats.accuracy > 0 && (
          <div className={styles.accuracyRow}>
            <span className={styles.accuracyLabel}>Trefferquote</span>
            <span className={`font-display ${styles.accuracyVal}`}>{stats.accuracy}%</span>
          </div>
        )}
      </div>

      {/* Tip history */}
      {recentTips.length > 0 && (
        <div className={`card ${styles.historyCard}`}>
          <h2 className={styles.sectionTitle}>Letzte Tipps</h2>
          <ul className={styles.tipList}>
            {recentTips.map((tip, i) => (
              <li key={tip.match_id} className={`${styles.tipRow} ${i % 2 === 1 ? styles.tipRowAlt : ''}`}>
                <span className={styles.tipMatch}>
                  {tip.home_team_short} vs {tip.away_team_short}
                </span>
                <span className={styles.tipScore}>
                  Tipp: {tip.tip_home}:{tip.tip_away}
                </span>
                <span className={`${styles.pointBadge} ${pointBadgeClass(tip.points)}`}>
                  {pointLabel(tip.points)}
                </span>
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Fun stats */}
      {tips.length > 0 && (
        <div className={styles.funStats}>
          <h2 className={styles.sectionTitle}>Fun Facts</h2>
          <div className={styles.funGrid}>
            <div className={`card ${styles.funCard}`}>
              <span className={styles.funIcon}>🎯</span>
              <span className={styles.funLabel}>Lieblings-Tipp</span>
              <span className={styles.funValue}>{favTip}</span>
            </div>
            <div className={`card ${styles.funCard}`}>
              <span className={styles.funIcon}>🏠</span>
              <span className={styles.funLabel}>Heimsiege getippt</span>
              <span className={styles.funValue}>{homePct}%</span>
            </div>
            <div className={`card ${styles.funCard}`}>
              <span className={styles.funIcon}>📊</span>
              <span className={styles.funLabel}>Tipps abgegeben</span>
              <span className={styles.funValue}>{stats.tipsCount}</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
