import Ionicons from '@expo/vector-icons/Ionicons';
import { router } from 'expo-router';
import { useState } from 'react';
import { Pressable, StyleSheet, TextInput, View } from 'react-native';

import { Card } from '@/components/card';
import { Screen } from '@/components/screen';
import { ThemedText } from '@/components/themed-text';
import { Fonts, Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { relativeDay } from '@/lib/format';
import { gameRecord, lastPlayed, useStore } from '@/lib/store';

export default function GamesScreen() {
  const theme = useTheme();
  const { state } = useStore();
  const [query, setQuery] = useState('');

  const games = state.games.filter((game) =>
    game.name.toLowerCase().includes(query.trim().toLowerCase()),
  );

  return (
    <Screen
      title="Games"
      subtitle={`${state.games.length} games · ${state.matches.length} matches`}>
      <View style={[styles.search, { backgroundColor: theme.backgroundSelected }]}>
        <Ionicons name="search" size={16} color={theme.textSecondary} />
        <TextInput
          value={query}
          onChangeText={setQuery}
          placeholder="Search games…"
          placeholderTextColor={theme.textSecondary}
          style={[styles.searchInput, { color: theme.text }]}
        />
      </View>

      <Card style={styles.listCard}>
        {games.length === 0 ? (
          <ThemedText type="small" themeColor="textSecondary" style={styles.empty}>
            No games match “{query}”.
          </ThemedText>
        ) : (
          games.map((game, i) => {
            const record = gameRecord(state, game.id);
            const played = lastPlayed(state, game.id);
            const leader =
              record.p1 === record.p2
                ? 'Tied'
                : record.p1 > record.p2
                  ? `${state.players.p1.name} leads`
                  : `${state.players.p2.name} leads`;
            return (
              <Pressable
                key={game.id}
                onPress={() => router.push(`/game/${game.id}`)}
                style={({ pressed }) => [
                  styles.row,
                  i > 0 && { borderTopWidth: 1, borderTopColor: theme.border },
                  pressed && { opacity: 0.6 },
                ]}>
                <View style={[styles.gameIcon, { backgroundColor: theme.backgroundSelected }]}>
                  <ThemedText style={styles.gameEmoji}>{game.emoji}</ThemedText>
                </View>
                <View style={styles.rowMeta}>
                  <ThemedText type="smallBold">{game.name}</ThemedText>
                  <ThemedText type="small" themeColor="textSecondary" style={styles.rowSub}>
                    {leader} {record.p1}–{record.p2}
                    {played ? ` · ${relativeDay(played)}` : ' · never played'}
                  </ThemedText>
                </View>
                <Ionicons name="chevron-forward" size={16} color={theme.textSecondary} />
              </Pressable>
            );
          })
        )}
      </Card>

      <Pressable
        onPress={() => router.push('/add-game')}
        style={({ pressed }) => [styles.addRow, pressed && { opacity: 0.6 }]}>
        <ThemedText type="smallBold" style={{ color: theme.felt }}>
          ＋ Add a game
        </ThemedText>
      </Pressable>
    </Screen>
  );
}

const styles = StyleSheet.create({
  search: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    borderRadius: 11,
    paddingHorizontal: 12,
  },
  searchInput: { flex: 1, paddingVertical: 10, fontSize: 14 },
  listCard: { paddingVertical: 2 },
  empty: { paddingVertical: Spacing.three },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 11,
    paddingVertical: 10,
  },
  gameIcon: {
    width: 36,
    height: 36,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  gameEmoji: { fontSize: 17 },
  rowMeta: { flex: 1 },
  rowSub: { fontFamily: Fonts?.mono, fontSize: 12 },
  addRow: { alignItems: 'center', paddingVertical: Spacing.two },
});
