import { View, Text, Pressable, ScrollView, RefreshControl } from "react-native";
import { useLocalSearchParams, Link } from "expo-router";
import { useState, useCallback } from "react";
import { useTheme } from "../../../components/theme";
import { usePaginatedQuery, useQuery } from "convex/react";
import { api } from "../../../convex/_generated/api";
import { CategoryGrid } from "../../../components/category-grid";
import { AdCard } from "../../../components/ad-card";
import { Loading } from "../../../components/ui/loading";
import { CATEGORIES, CATEGORY_EMOJI, getCategoryName } from "../../../lib/constants";

export default function ExploreScreen() {
  const theme = useTheme();
  const { category } = useLocalSearchParams<{ category?: string }>();
  const [refreshing, setRefreshing] = useState(false);

  const categories = useQuery(api.categories.list);
  const categoryAdsResult = usePaginatedQuery(
    api.ads.getByCategoryPaginated,
    category ? { category } : "skip",
    { initialNumItems: 20 }
  );
  const allAdsResult = usePaginatedQuery(api.ads.listPaginated, {}, { initialNumItems: 20 });

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    setTimeout(() => setRefreshing(false), 800);
  }, []);

  const displayCategories = categories ?? CATEGORIES;

  if (category) {
    const catName = getCategoryName(category);
    const catEmoji = CATEGORY_EMOJI[category] ?? "📋";

    return (
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md, paddingBottom: 40 }}
      >
        <View style={{ flexDirection: "row", alignItems: "center", gap: theme.spacing.sm }}>
          <Link href="/(tabs)/(explore)" asChild>
            <Pressable accessible accessibilityLabel="Назад кон сите категории" accessibilityRole="link" style={{ marginRight: theme.spacing.xs }}>
              <Text style={{ ...theme.typography.bodyBold, color: theme.colors.primary }}>← Сите</Text>
            </Pressable>
          </Link>
          <View
            style={{
              width: 40,
              height: 40,
              borderRadius: theme.radius.md,
              backgroundColor: theme.colors.primaryLight,
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Text style={{ fontSize: 22 }}>{catEmoji}</Text>
          </View>
          <Text selectable style={{ ...theme.typography.h2, color: theme.colors.text }}>
            {catName}
          </Text>
        </View>

        {categoryAdsResult.status === "LoadingFirstPage" ? (
          <Loading />
        ) : categoryAdsResult.results.length === 0 ? (
          <View style={{ alignItems: "center", paddingVertical: 60 }}>
            <Text style={{ fontSize: 48, marginBottom: theme.spacing.md }}>🔎</Text>
            <Text style={{ ...theme.typography.body, color: theme.colors.textTertiary, textAlign: "center" }}>
              Нема огласи во оваа категорија
            </Text>
          </View>
        ) : (
          <View style={{ gap: theme.spacing.sm }}>
            {categoryAdsResult.results.map((ad) => (
              <AdCard key={ad._id} ad={ad} />
            ))}
          </View>
        )}

        {categoryAdsResult.status === "CanLoadMore" && (
          <Pressable
            accessible
            accessibilityLabel="Вчитај повеќе огласи"
            accessibilityRole="button"
            onPress={() => categoryAdsResult.loadMore(20)}
            style={{
              backgroundColor: theme.colors.surfaceAlt,
              borderRadius: theme.radius.md,
              paddingVertical: theme.spacing.md,
              alignItems: "center",
              borderWidth: 1,
              borderColor: theme.colors.borderLight,
            }}
          >
            <Text style={{ color: theme.colors.primary, fontWeight: "600", fontSize: 15 }}>Вчитај повеќе</Text>
          </Pressable>
        )}
      </ScrollView>
    );
  }

  return (
    <ScrollView
      contentInsetAdjustmentBehavior="automatic"
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
      }
      contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md, paddingBottom: 40 }}
    >
      <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>
        Пребарувај по категорија
      </Text>

      <CategoryGrid categories={displayCategories} />

      <Text style={{ ...theme.typography.h2, color: theme.colors.text, marginTop: theme.spacing.sm }}>
        Сите огласи
      </Text>

      {allAdsResult.status === "LoadingFirstPage" ? (
        <Loading />
      ) : allAdsResult.results.length === 0 ? (
        <View style={{ alignItems: "center", paddingVertical: 60 }}>
          <Text style={{ fontSize: 48, marginBottom: theme.spacing.md }}>📦</Text>
          <Text style={{ ...theme.typography.body, color: theme.colors.textTertiary, textAlign: "center" }}>
            Нема огласи
          </Text>
        </View>
      ) : (
        <View style={{ gap: theme.spacing.sm }}>
          {allAdsResult.results.map((ad) => (
            <AdCard key={ad._id} ad={ad} />
          ))}
        </View>
      )}

      {allAdsResult.status === "CanLoadMore" && (
        <Pressable
          accessible
          accessibilityLabel="Вчитај повеќе огласи"
          accessibilityRole="button"
          onPress={() => allAdsResult.loadMore(20)}
          style={{
            backgroundColor: theme.colors.surfaceAlt,
            borderRadius: theme.radius.md,
            paddingVertical: theme.spacing.md,
            alignItems: "center",
            borderWidth: 1,
            borderColor: theme.colors.borderLight,
          }}
        >
          <Text style={{ color: theme.colors.primary, fontWeight: "600", fontSize: 15 }}>Вчитај повеќе</Text>
        </Pressable>
      )}
    </ScrollView>
  );
}
