import { View, Text, ScrollView, RefreshControl } from "react-native";
import { useRouter } from "expo-router";
import { useState, useCallback } from "react";
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "../../../components/theme";
import { usePaginatedQuery } from "convex/react";
import { api } from "../../../convex/_generated/api";
import { useAuth } from "../../_layout";
import { PostCard } from "../../../components/post-card";
import { Button } from "../../../components/ui/button";
import { Loading } from "../../../components/ui/loading";

export default function PostsScreen() {
  const theme = useTheme();
  const router = useRouter();
  const { isAuthenticated } = useAuth();
  const [refreshing, setRefreshing] = useState(false);

  const postsResult = usePaginatedQuery(
    api.posts.listPaginated,
    {},
    { initialNumItems: 20 }
  );

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

  if (!isAuthenticated) {
    return (
      <View style={{ flex: 1, backgroundColor: theme.colors.background }}>
        <View style={{ paddingHorizontal: theme.spacing.md, paddingTop: 60, paddingBottom: theme.spacing.md, backgroundColor: theme.colors.surface, ...theme.shadows.xs }}>
          <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>
            Побарувања
          </Text>
        </View>
        <View style={{ flex: 1, alignItems: "center", justifyContent: "center", padding: theme.spacing.lg }}>
          <View
            style={{
              width: 72,
              height: 72,
              borderRadius: 36,
              backgroundColor: theme.colors.primaryLight,
              alignItems: "center",
              justifyContent: "center",
              marginBottom: theme.spacing.md,
              ...theme.shadows.xs,
            }}
          >
            <Ionicons name="document-text" size={30} color={theme.colors.primary} />
          </View>
          <Text style={{ ...theme.typography.bodyBold, color: theme.colors.text, marginBottom: theme.spacing.xs }}>
            Потребна најава
          </Text>
          <Text style={{ ...theme.typography.caption, color: theme.colors.textSecondary, textAlign: "center", marginBottom: theme.spacing.lg }}>
            Најавете се за да ги видите побарувањата
          </Text>
          <Button onPress={() => router.push("/(auth)/login")}>
            Најави се
          </Button>
        </View>
      </View>
    );
  }

  return (
    <View style={{ flex: 1, backgroundColor: theme.colors.background }}>
      <View style={{ paddingHorizontal: theme.spacing.md, paddingTop: 60, paddingBottom: theme.spacing.md, backgroundColor: theme.colors.surface, ...theme.shadows.xs }}>
        <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>
          Побарувања
        </Text>
        <Text style={{ ...theme.typography.caption, color: theme.colors.textSecondary, marginTop: 4 }}>
          Побарувања од клиенти
        </Text>
      </View>

      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        contentContainerStyle={{ padding: theme.spacing.md, gap: theme.spacing.sm, paddingBottom: 100 }}
      >
        {postsResult.status === "LoadingFirstPage" ? (
          <Loading skeleton />
        ) : postsResult.results.length === 0 ? (
          <View style={{ alignItems: "center", paddingVertical: theme.spacing.xxl }}>
            <View
              style={{
                width: 72,
                height: 72,
                borderRadius: 36,
                backgroundColor: theme.colors.primaryLight,
                alignItems: "center",
                justifyContent: "center",
                marginBottom: theme.spacing.md,
                ...theme.shadows.xs,
              }}
            >
              <Ionicons name="document-text" size={30} color={theme.colors.primary} />
            </View>
            <Text style={{ ...theme.typography.bodyBold, color: theme.colors.text, marginBottom: theme.spacing.xs }}>
              Нема побарувања
            </Text>
            <Text style={{ ...theme.typography.caption, color: theme.colors.textSecondary, textAlign: "center" }}>
              Сè уште нема побарувања
            </Text>
          </View>
        ) : (
          postsResult.results.map((post) => (
            <PostCard key={post._id} post={post} />
          ))
        )}

        {postsResult.status === "CanLoadMore" && (
          <View style={{ alignItems: "center", marginTop: theme.spacing.sm }}>
            <Button
              variant="outline"
              size="sm"
              onPress={() => postsResult.loadMore(20)}
            >
              Вчитај повеќе
            </Button>
          </View>
        )}
      </ScrollView>
    </View>
  );
}
