import { StyleSheet, View } from 'react-native';

import { Card } from '@/components/card';
import { SectionLabel } from '@/components/section-label';
import { Screen } from '@/components/screen';
import { ThemedText } from '@/components/themed-text';
import { usePlayerColor } from '@/components/player-avatar';
import { Fonts, Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { relativeDay } from '@/lib/format';
import { currentStreak, gameRecord, overallTotals, useStore } from '@/lib/store';
import type { PlayerId } from '@/lib/types';

function RecordNumber({ value, leading, playerId }: { value: number; leading: boolean; playerId: PlayerId }) {
  const color = usePlayerColor(playerId);
  const theme = useTheme();
  return (
    <ThemedText style={[styles.recordNum, { color: leading ? color : theme.textSecondary }]}>
      {value}
    </ThemedText>
  );
}

export default function StandingsScreen() {
  const theme = useTheme();
  const { state } = useStore();
  const { players, games, matches } = state;
  const { wins, points, leaderId } = overallTotals(state);
  const streak = currentStreak(state);
  const latest = matches[0];
  const latestGame = latest && games.find((g) => g.id === latest.gameId);

  const totalDecided = wins.p1 + wins.p2;
  const p1Share = totalDecided === 0 ? 0.5 : wins.p1 / totalDecided;
  const headline =
    leaderId === null
      ? 'Dead even. For now.'
      : `${players[leaderId].name} leads by ${Math.abs(wins.p1 - wins.p2)} ${
          Math.abs(wins.p1 - wins.p2) === 1 ? 'win' : 'wins'
        } 👑`;

  return (
    <Screen title="Standings" subtitle={`${matches.length} matches logged`}>
      <View style={[styles.banner, { backgroundColor: theme.felt }]}>
        <ThemedText style={styles.bannerLabel}>All-time</ThemedText>
        <ThemedText style={styles.bannerHeadline}>{headline}</ThemedText>
        <View style={styles.duel}>
          <ThemedText style={styles.duelSide}>
            {players.p1.name} <ThemedText style={styles.duelNum}>{wins.p1}</ThemedText>
          </ThemedText>
          <ThemedText style={styles.duelVs}>wins</ThemedText>
          <ThemedText style={styles.duelSide}>
            <ThemedText style={styles.duelNum}>{wins.p2}</ThemedText> {players.p2.name}
          </ThemedText>
        </View>
        <View style={styles.meter}>
          <View style={[styles.meterFill, { flex: p1Share, backgroundColor: '#EFC75E' }]} />
          <View style={{ flex: 1 - p1Share }} />
        </View>
        <ThemedText style={styles.bannerPoints}>
          {points.p1.toLocaleString()} – {points.p2.toLocaleString()} total points
        </ThemedText>
      </View>

      <SectionLabel>Record by game</SectionLabel>
      <Card style={styles.recordCard}>
        {games.map((game, i) => {
          const record = gameRecord(state, game.id);
          return (
            <View
              key={game.id}
              style={[
                styles.recordRow,
                i > 0 && { borderTopWidth: 1, borderTopColor: theme.border },
              ]}>
              <ThemedText type="smallBold">
                {game.emoji} {game.name}
              </ThemedText>
              <View style={styles.recordNums}>
                <RecordNumber value={record.p1} leading={record.p1 > record.p2} playerId="p1" />
                <ThemedText themeColor="textSecondary" style={styles.recordDash}>
                  –
                </ThemedText>
                <RecordNumber value={record.p2} leading={record.p2 > record.p1} playerId="p2" />
              </View>
            </View>
          );
        })}
      </Card>

      <SectionLabel>Latest</SectionLabel>
      <Card>
        {latest && latestGame ? (
          <View style={{ gap: 2 }}>
            <ThemedText type="smallBold">
              {latest.winnerId ? players[latest.winnerId].name : 'Nobody'} won {latestGame.name}
            </ThemedText>
            <ThemedText type="small" themeColor="textSecondary" style={styles.mono}>
              {latest.scores.p1}–{latest.scores.p2} · {relativeDay(latest.playedAt)}
            </ThemedText>
            {streak && streak.length >= 3 ? (
              <ThemedText
                type="smallBold"
                style={{ color: playerColor(streak.holder, theme) }}>
                “{players[streak.holder].alias} is on a {streak.length}-game heater 🔥”
              </ThemedText>
            ) : null}
          </View>
        ) : (
          <ThemedText type="small" themeColor="textSecondary">
            No matches yet — go start a rivalry.
          </ThemedText>
        )}
      </Card>
    </Screen>
  );
}

function playerColor(playerId: PlayerId, theme: ReturnType<typeof useTheme>) {
  return playerId === 'p1' ? theme.playerOne : theme.playerTwo;
}

const styles = StyleSheet.create({
  banner: {
    borderRadius: 16,
    padding: Spacing.three,
    gap: 6,
  },
  bannerLabel: {
    color: 'rgba(255,255,255,0.85)',
    fontSize: 10,
    fontWeight: '700',
    letterSpacing: 1.4,
  },
  bannerHeadline: {
    color: '#FFFFFF',
    fontSize: 18,
    lineHeight: 24,
    fontWeight: '800',
  },
  duel: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'baseline',
    marginTop: 4,
  },
  duelSide: { color: '#FFFFFF', fontSize: 13, fontWeight: '600' },
  duelNum: { color: '#FFFFFF', fontSize: 20, fontWeight: '800', fontFamily: Fonts?.mono },
  duelVs: { color: 'rgba(255,255,255,0.7)', fontSize: 11 },
  meter: {
    flexDirection: 'row',
    height: 8,
    borderRadius: 99,
    backgroundColor: 'rgba(255,255,255,0.25)',
    overflow: 'hidden',
  },
  meterFill: { borderRadius: 99 },
  bannerPoints: {
    color: 'rgba(255,255,255,0.8)',
    fontSize: 11,
    fontFamily: Fonts?.mono,
  },
  recordCard: { paddingVertical: 2 },
  recordRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 10,
  },
  recordNums: { flexDirection: 'row', alignItems: 'baseline', gap: 4 },
  recordNum: { fontSize: 15, fontWeight: '800', fontFamily: Fonts?.mono },
  recordDash: { fontSize: 13 },
  mono: { fontFamily: Fonts?.mono },
});
