import { View, Text, TextInput, ScrollView, RefreshControl, Pressable } from "react-native";
import { useState, useCallback } from "react";
import { useTheme } from "../../../components/theme";
import { useQuery, usePaginatedQuery } 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 } from "../../../lib/constants";

export default function HomeScreen() {
  const theme = useTheme();
  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={{ padding: theme.spacing.lg, gap: theme.spacing.md, paddingBottom: 40 }}
    >
      <View style={{ marginTop: theme.spacing.md }}>
        <Text style={{ fontSize: 24, fontWeight: "700", color: theme.colors.text }}>
          Добредојдовте 🏠
        </Text>
        <Text selectable style={{ fontSize: 16, color: theme.colors.textSecondary, marginTop: theme.spacing.sm }}>
          Најдете мајстор во вашата близина
        </Text>
      </View>

      <TextInput
        accessible
        accessibilityLabel="Пребарувај мајстори"
        accessibilityRole="search"
        placeholder="Пребарувај мајстори..."
        placeholderTextColor={theme.colors.textTertiary}
        value={search}
        onChangeText={setSearch}
        style={{
          backgroundColor: theme.colors.surface,
          borderRadius: theme.radius.md,
          padding: theme.spacing.md,
          fontSize: 16,
          color: theme.colors.text,
          borderWidth: 1,
          borderColor: theme.colors.border,
        }}
      />

      {!search.trim() && (
        <>
          <Text style={{ fontSize: 18, fontWeight: "600", color: theme.colors.text, marginTop: theme.spacing.sm }}>
            Категории
          </Text>
          <CategoryGrid categories={displayCategories} />
        </>
      )}

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

      {(search.trim() ? searchResults === undefined : isLoading) ? (
        <Loading />
      ) : displayAds.length === 0 ? (
        <Text style={{ color: theme.colors.textTertiary, textAlign: "center", padding: 24 }}>
          {search.trim() ? "Не се пронајдени резултати" : "Нема огласи"}
        </Text>
      ) : (
        <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.surface,
            borderRadius: theme.radius.md,
            paddingVertical: theme.spacing.md,
            alignItems: "center",
            borderWidth: 1,
            borderColor: theme.colors.border,
          }}
        >
          <Text style={{ color: theme.colors.primary, fontWeight: "600", fontSize: 14 }}>Вчитај повеќе</Text>
        </Pressable>
      )}
    </ScrollView>
  );
}