import { View, Text, Pressable } from "react-native";
import { Link } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "./theme";
import { Badge } from "./ui/badge";
import { Rating } from "./ui/rating";
import { getCategoryName, CATEGORIES } from "../lib/constants";

interface AdCardProps {
  ad: {
    _id: string;
    title: string;
    category: string;
    location: string;
    priceRange?: string;
    ratingAvg?: number;
    reviewCount: number;
  };
}

function getCategoryIcon(slug: string): string {
  return CATEGORIES.find((c) => c.slug === slug)?.icon ?? "construct-outline";
}

function getCategoryColor(slug: string): string {
  const colors = ["#D4764A", "#4A8C6F", "#2B5797", "#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 AdCard({ ad }: AdCardProps) {
  const theme = useTheme();
  const categoryName = getCategoryName(ad.category);
  const iconName = getCategoryIcon(ad.category);
  const catColor = getCategoryColor(ad.category);

  return (
    <Link href={`/ad/${ad._id}` as any} asChild>
      <Pressable
        accessible
        accessibilityLabel={`${ad.title}, ${categoryName}, ${ad.location}${ad.priceRange ? `, ${ad.priceRange}` : ""}`}
        accessibilityRole="button"
        style={({ pressed }) => [
          {
            backgroundColor: theme.colors.surface,
            borderRadius: theme.radius.lg,
            padding: theme.spacing.md,
            borderWidth: 1,
            borderColor: theme.colors.border,
            ...theme.shadows.xs,
          },
          pressed && { opacity: 0.82, transform: [{ scale: 0.995 }] },
        ]}
      >
        <View style={{ flexDirection: "row", alignItems: "center", gap: theme.spacing.md }}>
          <View
            style={{
              width: 52,
              height: 52,
              borderRadius: theme.radius.md,
              backgroundColor: catColor + "14",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Ionicons name={iconName as any} size={24} color={catColor} />
          </View>
          <View style={{ flex: 1, gap: 3 }}>
            <Text style={{ ...theme.typography.bodyBold, color: theme.colors.text, fontSize: 15 }} numberOfLines={1}>
              {ad.title}
            </Text>
            <View style={{ flexDirection: "row", alignItems: "center", gap: theme.spacing.sm }}>
              <Ionicons name="location-outline" size={13} color={theme.colors.textTertiary} />
              <Text style={{ ...theme.typography.caption, color: theme.colors.textSecondary }}>
                {ad.location}
              </Text>
            </View>
            {ad.ratingAvg != null && ad.ratingAvg > 0 && (
              <Rating value={ad.ratingAvg} count={ad.reviewCount} size={13} />
            )}
          </View>
          <View style={{ alignItems: "flex-end", gap: 6 }}>
            {ad.priceRange && (
              <View style={{ backgroundColor: theme.colors.primaryLight, paddingHorizontal: 10, paddingVertical: 5, borderRadius: theme.radius.full }}>
                <Text style={{ ...theme.typography.captionBold, color: theme.colors.primary, fontSize: 12 }}>
                  {ad.priceRange}
                </Text>
              </View>
            )}
            <Badge label={categoryName} variant="default" size="sm" />
          </View>
        </View>
      </Pressable>
    </Link>
  );
}
