import { useRouter } from 'expo-router';
import { useCallback, useState } from 'react';
import { ScrollView, StyleSheet, Text, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { BrandPressable } from '@/components/brand-pressable';
import { BrandTextInput } from '@/components/brand-text-input';
import { GameTile } from '@/components/game-tile';
import { Brand, BrandFont } from '@/constants/theme';
import { filterGames } from '@/hooks/use-game-search';

/**
 * Frame `20-21` in the Figma. A single screen that combines the "search" and
 * "select" flows: the search input filters the grid below it, and the section
 * header swaps between "Most Popular" (empty query) and "Searched Results"
 * (non-empty query). Tapping a tile toggles its selection; the Continue
 * button at the bottom is disabled until at least one game is selected.
 */
export default function SelectGamesScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const [query, setQuery] = useState('');
  const [selected, setSelected] = useState<Set<string>>(new Set());

  const isEmpty = query.trim().length === 0;
  const results = filterGames(query);
  const sectionTitle = isEmpty ? 'Most Popular' : 'Searched Results';

  const toggle = useCallback((id: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  }, []);

  return (
    <View style={[styles.root, { paddingTop: insets.top, paddingBottom: insets.bottom }]}>
      <View style={styles.header}>
        <Text style={styles.title}>Which games do you play?</Text>
        <BrandTextInput
          placeholder="Search for games..."
          placeholderTextColor={Brand.textFaint}
          value={query}
          onChangeText={setQuery}
          leadingIcon="magnifyingglass"
          returnKeyType="search"
          autoCapitalize="none"
        />
      </View>

      <Text style={styles.sectionTitle}>{sectionTitle}</Text>

      <ScrollView
        contentContainerStyle={styles.grid}
        showsVerticalScrollIndicator={false}>
        {results.length === 0 ? (
          <Text style={styles.empty}>No games match “{query}”.</Text>
        ) : (
          results.map((game) => (
            <GameTile
              key={game.id}
              id={game.id}
              name={game.name}
              genre={game.genre}
              gradient={game.gradient}
              selected={selected.has(game.id)}
              onPress={() => toggle(game.id)}
            />
          ))
        )}
      </ScrollView>

      <View style={styles.footer}>
        <BrandPressable
          label={`Continue${selected.size > 0 ? ` (${selected.size})` : ''}`}
          disabled={selected.size === 0}
          onPress={() => router.push('/explore')}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  root: {
    flex: 1,
    backgroundColor: Brand.bg,
    paddingHorizontal: 24,
  },
  header: {
    paddingTop: 32,
    paddingBottom: 16,
    gap: 20,
  },
  title: {
    color: Brand.text,
    fontSize: 22,
    lineHeight: 28,
    fontFamily: BrandFont.montserratBold,
  },
  sectionTitle: {
    color: Brand.text,
    fontSize: 15,
    lineHeight: 20,
    fontFamily: BrandFont.poppinsSemiBold,
    paddingTop: 4,
    paddingBottom: 8,
  },
  grid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    paddingBottom: 16,
    rowGap: 16,
  },
  footer: {
    paddingTop: 12,
  },
  empty: {
    color: Brand.textMuted,
    fontSize: 14,
    lineHeight: 20,
    fontFamily: BrandFont.poppinsRegular,
    paddingTop: 32,
    textAlign: 'center',
    alignSelf: 'center',
  },
});
