// Lista tagów + tap → TagScenes. Domyślny order: popular (po liczbie scen desc).
// Layout: chip-grid, bo nazwy tagów są krótkie i upacking ich w listę marnuje miejsce.
import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useQuery } from '@tanstack/react-query';
import React, { useState } from 'react';
import {
  ActivityIndicator,
  FlatList,
  Pressable,
  StyleSheet,
  Text,
  TextInput,
  View,
} from 'react-native';
import { useClient } from '../ClientContext';
import type { RootStackParamList } from '../navigation';
import { theme } from '../theme';
import type { TagCount } from '../types';

type Order = 'popular' | 'name';

export function TagsScreen() {
  const client = useClient();
  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList, 'Tags'>>();
  const [q, setQ] = useState('');
  const [debouncedQ, setDebouncedQ] = useState('');
  const [order, setOrder] = useState<Order>('popular');
  const [searchFocused, setSearchFocused] = useState(false);

  React.useEffect(() => {
    const t = setTimeout(() => setDebouncedQ(q), 350);
    return () => clearTimeout(t);
  }, [q]);

  const { data, isLoading, error, refetch, isRefetching } = useQuery({
    queryKey: ['tags', debouncedQ, order],
    queryFn: () => client.listTags({ q: debouncedQ || undefined, order, per_page: 500 }),
  });

  const total = data?.items.length ?? 0;

  return (
    <View style={styles.container}>
      <View style={styles.headerRow}>
        <Text style={styles.headerLabel}>Tags</Text>
        <Text style={styles.headerCount}>{total}</Text>
      </View>
      <Text style={styles.hint}>tap a chip → filter scenes by tag</Text>

      <View style={styles.toolbar}>
        <TextInput
          style={[styles.search, searchFocused && styles.searchFocused]}
          value={q}
          onChangeText={setQ}
          onFocus={() => setSearchFocused(true)}
          onBlur={() => setSearchFocused(false)}
          placeholder="search tag…"
          placeholderTextColor={theme.mutedDim}
          autoCapitalize="none"
        />
      </View>

      <View style={styles.segment}>
        <SegButton
          active={order === 'popular'}
          onPress={() => setOrder('popular')}
          label="Top"
        />
        <SegButton
          active={order === 'name'}
          onPress={() => setOrder('name')}
          label="A–Z"
        />
      </View>

      {isLoading && <ActivityIndicator color={theme.fg} style={{ marginTop: 24 }} />}
      {error instanceof Error && <Text style={styles.error}>{error.message}</Text>}

      <FlatList
        data={data?.items ?? []}
        keyExtractor={(t) => t.id}
        numColumns={2}
        columnWrapperStyle={styles.gridRow}
        renderItem={({ item }) => (
          <TagChip
            tag={item}
            onPress={() =>
              navigation.navigate('TagScenes', { slug: item.slug, name: item.name })
            }
          />
        )}
        refreshing={isRefetching}
        onRefresh={refetch}
        ListEmptyComponent={!isLoading ? <Text style={styles.emptyText}>no tags</Text> : null}
        contentContainerStyle={{ paddingBottom: 24 }}
      />
    </View>
  );
}

function SegButton({
  active,
  onPress,
  label,
}: {
  active: boolean;
  onPress: () => void;
  label: string;
}) {
  return (
    <Pressable
      onPress={onPress}
      style={[styles.segButton, active && styles.segButtonActive]}
    >
      <Text style={[styles.segButtonText, active && styles.segButtonTextActive]}>
        {label}
      </Text>
    </Pressable>
  );
}

function TagChip({ tag, onPress }: { tag: TagCount; onPress: () => void }) {
  return (
    <Pressable
      style={({ pressed }) => [styles.chip, pressed && styles.chipPressed]}
      onPress={onPress}
    >
      <Text style={styles.chipName} numberOfLines={1}>
        {tag.name}
      </Text>
      <View style={styles.chipCountWrap}>
        <Text style={styles.chipCount}>{tag.scene_count}</Text>
      </View>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: theme.bg, paddingHorizontal: 16, paddingTop: 12 },

  headerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingBottom: 4,
  },
  headerLabel: {
    color: theme.muted,
    fontSize: 12,
    textTransform: 'uppercase',
    letterSpacing: 1.2,
    fontWeight: '700',
  },
  headerCount: { color: theme.fg, fontSize: 22, fontWeight: '800' },
  hint: { color: theme.mutedDim, fontSize: 11, marginBottom: 12 },

  toolbar: { flexDirection: 'row', gap: 12, marginBottom: 10 },
  search: {
    flex: 1,
    backgroundColor: theme.card,
    borderColor: theme.border,
    borderWidth: 1.5,
    borderRadius: 12,
    color: theme.fg,
    padding: 12,
    fontSize: 16,
  },
  searchFocused: { borderColor: theme.borderFocus },

  segment: {
    flexDirection: 'row',
    backgroundColor: theme.bgElevated,
    borderColor: theme.border,
    borderWidth: 1,
    borderRadius: 12,
    padding: 4,
    marginBottom: 14,
    alignSelf: 'flex-start',
  },
  segButton: { paddingHorizontal: 14, paddingVertical: 6, borderRadius: 8 },
  segButtonActive: {
    backgroundColor: theme.accent,
    shadowColor: theme.accent,
    shadowOffset: { width: 0, height: 0 },
    shadowOpacity: 0.4,
    shadowRadius: 6,
    elevation: 2,
  },
  segButtonText: { color: theme.muted, fontWeight: '700', fontSize: 13 },
  segButtonTextActive: { color: theme.fg },

  gridRow: { gap: 10, marginBottom: 10 },
  chip: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 8,
    backgroundColor: theme.card,
    borderColor: theme.border,
    borderWidth: 1,
    borderRadius: 12,
    paddingHorizontal: 12,
    paddingVertical: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.18,
    shadowRadius: 3,
    elevation: 2,
  },
  chipPressed: { borderColor: theme.borderFocus, backgroundColor: theme.bgElevated },
  chipName: {
    color: theme.fg,
    fontWeight: '600',
    fontSize: 14,
    flex: 1,
  },
  chipCountWrap: {
    backgroundColor: `${theme.accentSecondary}1F`,
    borderColor: `${theme.accentSecondary}55`,
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 8,
    paddingVertical: 2,
    minWidth: 36,
    alignItems: 'center',
  },
  chipCount: {
    color: theme.accentSecondary,
    fontSize: 12,
    fontWeight: '700',
  },

  emptyText: { color: theme.muted, textAlign: 'center', marginTop: 48, fontSize: 16 },
  error: { color: theme.bad, padding: 16 },
});
