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

export default function HomeScreen() {
  const theme = useTheme();
  const router = useRouter();
  const { userId } = useAuth();
  const [search, setSearch] = useState("");
  const [refreshing, setRefreshing] = useState(false);

  const categories = useQuery(api.categories.list);
  const adsResult = usePaginatedQuery(api.ads.listPaginated, {}, { initialNumItems: 20 });
  const ads = adsResult.results;
  const loadMoreAds = adsResult.loadMore;
  const adsStatus = adsResult.status;

  const searchResults = useQuery(
    api.ads.search,
    search.trim() ? { query: search.trim() } : "skip"
  );

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

  const displayCategories = categories ?? CATEGORIES;
  const displayAds = search.trim() ? (searchResults ?? []) : ads;

  const isLoading = !search.trim() && adsStatus === "LoadingFirstPage";

  return (
    <ScrollView
      contentInsetAdjustmentBehavior="automatic"
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
      }
      contentContainerStyle={{ paddingBottom: 40 }}
    >
      <View style={{ padding: theme.spacing.lg, gap: theme.spacing.md }}>
        <View style={{ marginTop: theme.spacing.md }}>
          <Text style={{ ...theme.typography.h1, color: theme.colors.text }}>
            Добредојдовте
          </Text>
          <Text selectable style={{ ...theme.typography.body, color: theme.colors.textSecondary, marginTop: theme.spacing.xs }}>
            Најдете мајстор во вашата близина
          </Text>
        </View>

        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            backgroundColor: theme.colors.surface,
            borderRadius: theme.radius.md,
            borderWidth: 1.5,
            borderColor: theme.colors.borderLight,
            paddingHorizontal: theme.spacing.md,
            gap: theme.spacing.sm,
          }}
        >
          <Text style={{ fontSize: 18 }}>🔍</Text>
          <TextInput
            accessible
            accessibilityLabel="Пребарувај мајстори"
            accessibilityRole="search"
            placeholder="Пребарувај мајстори..."
            placeholderTextColor={theme.colors.textTertiary}
            value={search}
            onChangeText={setSearch}
            style={{
              flex: 1,
              paddingVertical: 14,
              fontSize: 16,
              color: theme.colors.text,
            }}
          />
          {search.length > 0 && (
            <Pressable
              accessible
              accessibilityLabel="Исчисти пребарување"
              onPress={() => setSearch("")}
              style={{ padding: 4 }}
            >
              <Text style={{ color: theme.colors.textTertiary, fontSize: 18 }}>✕</Text>
            </Pressable>
          )}
        </View>

        {!search.trim() && (
          <>
            <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
              <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>
                Категории
              </Text>
              <Pressable
                accessible
                accessibilityLabel="Види ги сите категории"
                accessibilityRole="button"
                onPress={() => router.push("/(tabs)/(explore)")}
              >
                <Text style={{ ...theme.typography.bodyBold, color: theme.colors.primary }}>
                  Сите
                </Text>
              </Pressable>
            </View>
            <CategoryGrid categories={displayCategories} />
          </>
        )}

        <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>
          {search.trim() ? "Резултати од пребарување" : "Неодамна додадени"}
        </Text>

        {(search.trim() ? searchResults === undefined : isLoading) ? (
          <Loading />
        ) : displayAds.length === 0 ? (
          <View style={{ alignItems: "center", paddingVertical: theme.spacing.xl }}>
            <Text style={{ fontSize: 48, marginBottom: theme.spacing.md }}>🔎</Text>
            <Text style={{ ...theme.typography.body, color: theme.colors.textTertiary, textAlign: "center" }}>
              {search.trim() ? "Не се пронајдени резултати" : "Нема огласи"}
            </Text>
          </View>
        ) : (
          <View style={{ gap: theme.spacing.sm }}>
            {displayAds.map((ad) => (
              <AdCard key={ad._id} ad={ad} />
            ))}
          </View>
        )}

        {!search.trim() && adsStatus === "CanLoadMore" && (
          <Pressable
            accessible
            accessibilityLabel="Вчитај повеќе огласи"
            accessibilityRole="button"
            onPress={() => loadMoreAds(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>
        )}
      </View>
    </ScrollView>
  );
}
