import { View, Text, Pressable } from "react-native";
import { Link } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "./theme";

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

interface CategoryGridProps {
  categories: readonly CategoryItem[];
}

const CATEGORY_COLORS = [
  "#D4764A", "#4A8C6F", "#2B5797", "#C47A4A", "#8B5CF6", "#E07B5A",
  "#3B82F6", "#7C3AED", "#06B6D4", "#D97706", "#059669", "#6B7280",
];

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

  return (
    <View style={{ flexDirection: "row", flexWrap: "wrap", gap: theme.spacing.sm }}>
      {categories.map((cat) => {
        const colorIdx = cat.slug.split("").reduce((a, c) => a + c.charCodeAt(0), 0) % CATEGORY_COLORS.length;
        const color = CATEGORY_COLORS[colorIdx];

        return (
          <Link key={cat.slug} href={`/(tabs)/(explore)?category=${cat.slug}`} asChild>
            <Pressable
              accessible
              accessibilityLabel={cat.name}
              accessibilityRole="button"
              style={({ pressed }) => [
                {
                  width: "31%",
                  backgroundColor: theme.colors.surface,
                  borderRadius: theme.radius.lg,
                  padding: theme.spacing.md,
                  borderWidth: 1,
                  borderColor: theme.colors.border,
                  ...theme.shadows.xs,
                  alignItems: "center",
                },
                pressed && { opacity: 0.8, transform: [{ scale: 0.97 }] },
              ]}
            >
              <View
                style={{
                  width: 44,
                  height: 44,
                  borderRadius: theme.radius.md,
                  backgroundColor: color + "14",
                  alignItems: "center",
                  justifyContent: "center",
                  marginBottom: theme.spacing.sm,
                }}
              >
                <Ionicons name={(cat.icon as any) ?? "construct-outline"} size={22} color={color} />
              </View>
              <Text
                style={{
                  ...theme.typography.caption,
                  color: theme.colors.text,
                  textAlign: "center",
                  fontWeight: "500",
                }}
                numberOfLines={2}
              >
                {cat.name}
              </Text>
            </Pressable>
          </Link>
        );
      })}
    </View>
  );
}
