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

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

/**
 * Frames `24-101` (empty search + Most Popular), `29-3` ("Pubg|" + Most
 * Popular), and `29-37` ("Pubg|" + Searched Results). All three are the same
 * screen with different local search state; the section header swaps based on
 * whether the query has results that aren't the popular set.
 */
export default function SearchGamesScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const [query, setQuery] = useState('');
  const results = useGameSearch(query);
  const isEmpty = query.trim().length === 0;
  const sectionTitle = isEmpty ? 'Most Popular' : 'Searched Results';

  return (
    <View style={[styles.root, { paddingTop: insets.top, paddingBottom: insets.bottom }]}>
      <View style={styles.searchRow}>
        <BrandTextInput
          autoFocus
          placeholder="Search games by name"
          value={query}
          onChangeText={setQuery}
          leadingIcon="magnifyingglass"
          returnKeyType="search"
          autoCapitalize="none"
        />
      </View>

      <View style={styles.headerRow}>
        <Text style={styles.sectionTitle}>{sectionTitle}</Text>
        <Text onPress={() => router.back()} style={styles.cancel}>
          Cancel
        </Text>
      </View>

      <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}
              onPress={() => {
                // Demo: a tap on a result just clears the query so the user
                // can try another search. Real apps would add the game.
                setQuery('');
              }}
            />
          ))
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  root: {
    flex: 1,
    backgroundColor: Brand.bg,
    paddingHorizontal: 24,
  },
  searchRow: {
    paddingTop: 8,
    paddingBottom: 12,
  },
  headerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingBottom: 12,
  },
  sectionTitle: {
    color: Brand.text,
    fontSize: 18,
    lineHeight: 24,
    fontFamily: BrandFont.poppinsSemiBold,
  },
  cancel: {
    color: Brand.textMuted,
    fontSize: 13,
    lineHeight: 18,
    fontFamily: BrandFont.poppinsMedium,
    padding: 4,
  },
  grid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    paddingBottom: 24,
    rowGap: 16,
  },
  empty: {
    color: Brand.textMuted,
    fontSize: 14,
    lineHeight: 20,
    fontFamily: BrandFont.poppinsRegular,
    paddingTop: 32,
    textAlign: 'center',
    alignSelf: 'center',
  },
});
