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

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

export default function ProfilePage() {
  const [stats, setStats]         = useState<UserStats | null>(null);
  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(() => {
    api.getMyStats().then(s => {
      setStats(s);
      setTeamValue(s.team ?? '');
    }).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 evaluated = stats.exactCount + stats.tendencyCount + stats.wrongCount;

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

      {/* Hero 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-Feld */}
          <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 className={styles.heroPoints}>
          <span className={`font-display ${styles.pointsVal}`}>{stats.totalPoints}</span>
          <span className={styles.pointsLbl}>Punkte</span>
        </div>
      </div>

      {/* Stats grid */}
      <div className={styles.statsGrid}>
        <div className={`card ${styles.statCard}`}>
          <span className={`font-display ${styles.statVal} text-gold`}>{stats.exactCount}</span>
          <span className={styles.statLbl}>🎯 Exakt</span>
        </div>
        <div className={`card ${styles.statCard}`}>
          <span className={`font-display ${styles.statVal} text-primary`}>{stats.tendencyCount}</span>
          <span className={styles.statLbl}>✓ Tendenz</span>
        </div>
        <div className={`card ${styles.statCard}`}>
          <span className={`font-display ${styles.statVal}`} style={{ color: 'var(--error)' }}>{stats.wrongCount}</span>
          <span className={styles.statLbl}>✗ Falsch</span>
        </div>
        <div className={`card ${styles.statCard}`}>
          <span className={`font-display ${styles.statVal}`}>{stats.tipsCount}</span>
          <span className={styles.statLbl}>Tipps gesamt</span>
        </div>
      </div>

      {/* Accuracy bar */}
      {evaluated > 0 && (
        <div className={`card ${styles.accuracyCard}`}>
          <div className={styles.accuracyHeader}>
            <span className={styles.accuracyLabel}>Trefferquote</span>
            <span className={`font-display ${styles.accuracyVal}`}>{stats.accuracy}%</span>
          </div>
          <div className={styles.bar}>
            <div className={`${styles.barFill} ${styles.exact}`}
              style={{ width: `${(stats.exactCount / evaluated) * 100}%` }} />
            <div className={`${styles.barFill} ${styles.tendency}`}
              style={{ width: `${(stats.tendencyCount / evaluated) * 100}%` }} />
          </div>
          <div className={styles.barLegend}>
            <span><span className={styles.dot} style={{ background: 'var(--gold)' }} /> Exakt</span>
            <span><span className={styles.dot} style={{ background: 'var(--primary)' }} /> Tendenz</span>
            <span><span className={styles.dot} style={{ background: 'var(--surface-high)' }} /> Falsch</span>
          </div>
        </div>
      )}
    </div>
  );
}
