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

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 (
          <Touchable
            key={cat.id}
            onPress={() => onSelect(cat)}
            style={[
              styles.item,
              {
                backgroundColor: active ? color + '15' : theme.colors.bgTertiary,
                borderColor: active ? color : theme.colors.border,
              }
            ]}
          >
            <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>
          </Touchable>
        );
      })}
    </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,
  },
});
