import { Stack, useLocalSearchParams } from 'expo-router';
import { StyleSheet, View } from 'react-native';

import { Card } from '@/components/card';
import { SectionLabel } from '@/components/section-label';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { Fonts, MaxContentWidth, Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { shortDate } from '@/lib/format';
import { currentStreak, gameRecord, matchesForGame, useStore } from '@/lib/store';
import { ScrollView } from 'react-native';

export default function GameDetailScreen() {
  const theme = useTheme();
  const { id } = useLocalSearchParams<{ id: string }>();
  const { state } = useStore();
  const game = state.games.find((g) => g.id === id);

  if (!game) {
    return (
      <ThemedView style={styles.missing}>
        <ThemedText themeColor="textSecondary">Game not found.</ThemedText>
      </ThemedView>
    );
  }

  const { players } = state;
  const record = gameRecord(state, game.id);
  const streak = currentStreak(state, game.id);
  const history = matchesForGame(state, game.id);
  const recent = history.slice(0, 12).reverse();
  const maxScore = Math.max(1, ...recent.map((m) => Math.max(m.scores.p1, m.scores.p2)));

  return (
    <ThemedView style={styles.container}>
      <Stack.Screen options={{ title: `${game.emoji} ${game.name}` }} />
      <ScrollView contentContainerStyle={styles.scroll}>
        <View style={styles.content}>
          <Card style={styles.h2h}>
            <View style={styles.h2hSide}>
              <ThemedText type="smallBold" style={{ color: theme.playerOne }}>
                {players.p1.name}
              </ThemedText>
              <ThemedText style={[styles.h2hBig, { color: theme.playerOne }]}>
                {record.p1}
              </ThemedText>
            </View>
            <View style={styles.h2hMid}>
              <ThemedText type="small" themeColor="textSecondary">
                W – L
              </ThemedText>
              {record.ties > 0 ? (
                <ThemedText type="small" themeColor="textSecondary">
                  {record.ties} ties
                </ThemedText>
              ) : null}
            </View>
            <View style={styles.h2hSide}>
              <ThemedText type="smallBold" style={{ color: theme.playerTwo }}>
                {players.p2.name}
              </ThemedText>
              <ThemedText style={[styles.h2hBig, { color: theme.playerTwo }]}>
                {record.p2}
              </ThemedText>
            </View>
          </Card>

          {streak && streak.length >= 2 ? (
            <View
              style={[
                styles.streak,
                {
                  backgroundColor:
                    streak.holder === 'p1' ? theme.playerOneSoft : theme.playerTwoSoft,
                },
              ]}>
              <ThemedText
                type="smallBold"
                style={{
                  color: streak.holder === 'p1' ? theme.playerOne : theme.playerTwo,
                }}>
                🔥 {players[streak.holder].name} has won {streak.length} straight
              </ThemedText>
            </View>
          ) : null}

          {recent.length > 0 ? (
            <>
              <SectionLabel>{`Last ${recent.length} results`}</SectionLabel>
              <Card>
                <View style={styles.bars}>
                  {recent.map((match) => {
                    const winnerScore = match.winnerId
                      ? match.scores[match.winnerId]
                      : Math.max(match.scores.p1, match.scores.p2);
                    const height = 18 + (winnerScore / maxScore) * 36;
                    const color =
                      match.winnerId === 'p1'
                        ? theme.playerOne
                        : match.winnerId === 'p2'
                          ? theme.playerTwo
                          : theme.textSecondary;
                    return (
                      <View
                        key={match.id}
                        style={[styles.bar, { height, backgroundColor: color }]}
                      />
                    );
                  })}
                </View>
              </Card>
            </>
          ) : null}

          <SectionLabel>History</SectionLabel>
          <Card style={styles.historyCard}>
            {history.length === 0 ? (
              <ThemedText type="small" themeColor="textSecondary" style={styles.empty}>
                No matches yet. Scared?
              </ThemedText>
            ) : (
              history.map((match, i) => {
                const winner = match.winnerId ? players[match.winnerId] : null;
                return (
                  <View
                    key={match.id}
                    style={[
                      styles.historyRow,
                      i > 0 && { borderTopWidth: 1, borderTopColor: theme.border },
                    ]}>
                    <ThemedText type="small" themeColor="textSecondary" style={styles.hDate}>
                      {shortDate(match.playedAt)}
                    </ThemedText>
                    <ThemedText type="smallBold" style={styles.hScore}>
                      {match.scores.p1}–{match.scores.p2}
                      {match.dispute ? ' 🚩' : ''}
                    </ThemedText>
                    <View
                      style={[
                        styles.winPill,
                        {
                          backgroundColor: !winner
                            ? theme.backgroundSelected
                            : match.winnerId === 'p1'
                              ? theme.playerOneSoft
                              : theme.playerTwoSoft,
                        },
                      ]}>
                      <ThemedText
                        style={[
                          styles.winPillText,
                          {
                            color: !winner
                              ? theme.textSecondary
                              : match.winnerId === 'p1'
                                ? theme.playerOne
                                : theme.playerTwo,
                          },
                        ]}>
                        {winner ? winner.name.toUpperCase() : 'TIE'}
                      </ThemedText>
                    </View>
                  </View>
                );
              })
            )}
          </Card>
        </View>
      </ScrollView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  missing: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  scroll: { paddingVertical: Spacing.three, paddingBottom: Spacing.five },
  content: {
    width: '100%',
    maxWidth: MaxContentWidth,
    alignSelf: 'center',
    paddingHorizontal: Spacing.three,
    gap: Spacing.two,
  },
  h2h: { flexDirection: 'row', alignItems: 'center' },
  h2hSide: { flex: 1, alignItems: 'center', gap: 2 },
  h2hMid: { alignItems: 'center', gap: 2 },
  h2hBig: { fontSize: 34, lineHeight: 40, fontWeight: '800', fontFamily: Fonts?.mono },
  streak: {
    alignSelf: 'center',
    borderRadius: 99,
    paddingHorizontal: 14,
    paddingVertical: 6,
  },
  bars: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    gap: 4,
    height: 60,
  },
  bar: { flex: 1, borderTopLeftRadius: 3, borderTopRightRadius: 3 },
  historyCard: { paddingVertical: 2 },
  historyRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 9,
    gap: 8,
  },
  hDate: { width: 52, fontSize: 12 },
  hScore: { flex: 1, fontFamily: Fonts?.mono },
  winPill: { borderRadius: 6, paddingHorizontal: 7, paddingVertical: 2 },
  winPillText: { fontSize: 10, fontWeight: '800' },
  empty: { paddingVertical: Spacing.three },
});
