import React from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity } from 'react-native';
import { useRouter } from 'expo-router';
import { useUniqueCategories } from '@/hooks/useDatabase';
import { useSettings, ThemeColors } from '@/theme';
import Svg, { Path, Circle } from 'react-native-svg';

interface CategoryFilterProps {
  selected: string[];
  onSelect: (categoryIds: string[]) => void;
}

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

  const selectedSet = new Set(selected);
  const isAnythingSelected = selected.length > 0;

  const toggle = (id: string) => {
    const next = new Set(selectedSet);
    if (next.has(id)) {
      next.delete(id);
    } else {
      next.add(id);
    }
    onSelect(Array.from(next));
  };

  return (
    <ScrollView
      horizontal
      showsHorizontalScrollIndicator={false}
      contentContainerStyle={styles.container}
      style={styles.scrollView}
    >
      <CategoryButton
        id="all"
        name="All"
        color="#9E9E9E"
        selected={!isAnythingSelected}
        onPress={() => onSelect([])}
        theme={theme}
      />
      {categories.map((category) => (
        <CategoryButton
          key={category.id}
          id={category.id}
          name={category.name}
          color={category.color}
          selected={selectedSet.has(category.id)}
          onPress={() => toggle(category.id)}
          theme={theme}
        />
      ))}
      <TouchableOpacity
        style={[styles.manageButton, { borderColor: theme.borderStrong, backgroundColor: theme.cardAlt }]}
        onPress={() => router.push('/settings')}
        activeOpacity={0.7}
        accessibilityRole="button"
        accessibilityLabel="Manage categories"
        hitSlop={{ top: 8, bottom: 8, left: 4, right: 4 }}
      >
        <Svg width={14} height={14} viewBox="0 0 24 24">
          <Circle cx={12} cy={12} r={9} stroke={theme.textSecondary} strokeWidth={2.2} fill="none" />
          <Circle cx={12} cy={8.5} r={1.2} fill={theme.textSecondary} />
          <Circle cx={12} cy={15.5} r={1.2} fill={theme.textSecondary} />
          <Path d="M7.8 6.2l1 1.7M16.2 16.1l1 1.7M7.8 17.8l1-1.7M16.2 7.9l1-1.7" stroke={theme.textSecondary} strokeWidth={1.8} strokeLinecap="round" />
        </Svg>
        <Text style={[styles.manageLabel, { color: theme.textSecondary }]}>Manage</Text>
      </TouchableOpacity>
    </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}
      hitSlop={{ top: 6, bottom: 6, left: 4, right: 4 }}
    >
      <View
        style={[
          styles.colorDot,
          { backgroundColor: color },
        ]}
      />
      <Text style={[
        styles.buttonText,
        { color: theme.textSecondary },
        selected && { color: theme.text, fontWeight: '600' },
      ]}>
        {name}
      </Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  scrollView: {
    paddingVertical: 6,
  },
  container: {
    paddingHorizontal: 12,
    gap: 8,
    alignItems: 'center',
  },
  button: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 10,
    borderRadius: 18,
    borderWidth: 1.5,
    minHeight: 38,
    justifyContent: 'center',
    gap: 8,
  },
  colorDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
  },
  buttonText: {
    fontSize: 12,
    fontWeight: '500',
  },
  manageButton: {
    alignSelf: 'center',
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    paddingHorizontal: 12,
    paddingVertical: 10,
    borderRadius: 18,
    borderWidth: 1,
    borderStyle: 'dashed',
    minHeight: 38,
    justifyContent: 'center',
  },
  manageLabel: {
    fontSize: 12,
    fontWeight: '600',
  },
});