import React from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../theme';
import { getCategoryColor } from '../theme/palette';
import type { Category } from '../domain/categories';
import { CategoryIcon } from './CategoryIcon';

interface CategoryPickerProps {
  categories: Category[];
  selectedId?: string;
  onSelect: (cat: Category) => void;
}

/** 分类选择器（网格卡片化布局）。 */
export function CategoryPicker({ categories, selectedId, onSelect }: CategoryPickerProps) {
  const { theme } = useTheme();
  
  return (
    <View style={styles.grid}>
      {categories.map(cat => {
        const active = cat.id === selectedId;
        const color = getCategoryColor(cat.id);
        
        return (
          <Pressable
            key={cat.id}
            onPress={() => onSelect(cat)}
            style={({ pressed }) => [
              styles.item,
              {
                backgroundColor: active ? color + '15' : theme.colors.bgTertiary,
                borderColor: active ? color : theme.colors.border,
                opacity: pressed ? 0.75 : 1,
              }
            ]}
          >
            <CategoryIcon categoryId={cat.id} size={32} />
            <Text
              style={[
                styles.label,
                {
                  color: active ? theme.colors.fgPrimary : theme.colors.fgSecondary,
                  fontWeight: active ? '700' : '500',
                }
              ]}
              numberOfLines={1}
            >
              {cat.name}
            </Text>
          </Pressable>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  grid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
    paddingVertical: 4,
  },
  item: {
    width: '23%', // 约 4 列排布
    aspectRatio: 1,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 12,
    borderWidth: 1,
    gap: 6,
    padding: 4,
  },
  label: {
    fontSize: 12,
  },
});
