import { View, Text, Pressable } from "react-native";
import { Link } from "expo-router";
import { useTheme } from "./theme";
import { CATEGORY_EMOJI } from "../lib/constants";

interface CategoryItem {
  slug: string;
  name: string;
  icon?: string;
  sortOrder: number;
}

interface CategoryGridProps {
  categories: readonly CategoryItem[];
  columns?: number;
}

function getCategoryColor(slug: string): string {
  const colors = ["#D4764A", "#2B5797", "#4A8C6F", "#C47A4A", "#8B5CF6", "#E07B5A",
                   "#3B82F6", "#7C3AED", "#06B6D4", "#D97706", "#059669", "#6B7280"];
  const idx = slug.split("").reduce((a, c) => a + c.charCodeAt(0), 0);
  return colors[idx % colors.length];
}

export function CategoryGrid({ categories, columns = 3 }: CategoryGridProps) {
  const theme = useTheme();

  return (
    <View style={{ flexDirection: "row", flexWrap: "wrap", gap: theme.spacing.sm }}>
      {categories.map((cat) => {
        const emoji = CATEGORY_EMOJI[cat.slug] ?? cat.icon ?? "📋";
        const color = getCategoryColor(cat.slug);
        return (
          <Link key={cat.slug} href={`/(tabs)/(explore)?category=${cat.slug}`} asChild>
            <Pressable
              accessible
              accessibilityLabel={cat.name}
              accessibilityRole="button"
              style={{
                backgroundColor: theme.colors.surface,
                borderRadius: theme.radius.md,
                paddingVertical: theme.spacing.md,
                paddingHorizontal: theme.spacing.xs,
                borderWidth: 1,
                borderColor: theme.colors.borderLight,
                width: `${Math.floor((100 - (columns - 1) * 3.3) / columns)}%` as any,
                alignItems: "center",
                gap: 6,
              }}
            >
              <View
                style={{
                  width: 44,
                  height: 44,
                  borderRadius: 22,
                  backgroundColor: color + "18",
                  alignItems: "center",
                  justifyContent: "center",
                }}
              >
                <Text style={{ fontSize: 22 }}>{emoji}</Text>
              </View>
              <Text
                style={{
                  color: theme.colors.text,
                  fontSize: 12,
                  fontWeight: "600",
                  textAlign: "center",
                  lineHeight: 16,
                }}
                numberOfLines={2}
              >
                {cat.name}
              </Text>
            </Pressable>
          </Link>
        );
      })}
    </View>
  );
}
