import React from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity } from 'react-native';
import { useUniqueCategories } from '@/hooks/useDatabase';
import { useSettings, ThemeColors } from '@/theme';
import Category from '@/models/Category';

interface CategoryFilterProps {
  selected: string;
  onSelect: (categoryId: string) => void;
}

export function CategoryFilter({ selected, onSelect }: CategoryFilterProps) {
  const categories = useUniqueCategories();
  const { theme } = useSettings();

  if (categories.length === 0) {
    return null;
  }

  return (
    <ScrollView
      horizontal
      showsHorizontalScrollIndicator={false}
      contentContainerStyle={styles.container}
      style={styles.scrollView}
    >
      <CategoryButton
        id="all"
        name="All"
        color="#9E9E9E"
        selected={selected === 'all'}
        onPress={() => onSelect('all')}
        theme={theme}
      />
      {categories.map((category) => (
        <CategoryButton
          key={category.id}
          id={category.id}
          name={category.name}
          color={category.color}
          selected={selected === category.id}
          onPress={() => onSelect(category.id)}
          theme={theme}
        />
      ))}
    </ScrollView>
  );
}

interface CategoryButtonProps {
  id: string;
  name: string;
  color: string;
  selected: boolean;
  onPress: () => void;
  theme: ThemeColors;
}

function CategoryButton({ name, color, selected, onPress, theme }: CategoryButtonProps) {
  return (
    <TouchableOpacity
      style={[
        styles.button,
        { backgroundColor: theme.card, borderColor: theme.borderStrong },
        selected && { borderColor: theme.accent, backgroundColor: theme.accentSoft },
      ]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View
        style={[
          styles.colorDot,
          { backgroundColor: color },
          selected && styles.colorDotSelected,
        ]}
      />
      <Text style={[
        styles.buttonText,
        { color: theme.textSecondary },
        selected && { color: theme.accent, fontWeight: '600' },
      ]}>
        {name}
      </Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  scrollView: {
    paddingVertical: 0,
    marginBottom: 0,
  },
  container: {
    paddingHorizontal: 12,
    paddingTop: 0,
    paddingBottom: 0,
    gap: 6,
    alignItems: 'flex-start',
  },
  button: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 16,
    borderWidth: 1,
    minWidth: 64,
    justifyContent: 'center',
    gap: 6,
  },
  colorDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
  },
  colorDotSelected: {
    width: 10,
    height: 10,
    borderRadius: 5,
  },
  buttonText: {
    fontSize: 12,
    fontWeight: '500',
  },
});
