import { View, Text, ScrollView, RefreshControl } from "react-native";
import { useRouter } from "expo-router";
import { useState, useCallback } from "react";
import { useQuery } from "convex/react";
import { api } from "../../../convex/_generated/api";
import { useAuth } from "../../_layout";
import { useTheme } from "../../../components/theme";
import { ChatListItem } from "../../../components/chat-list-item";
import { Button } from "../../../components/ui/button";
import { Loading } from "../../../components/ui/loading";

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

  const chats = useQuery(
    api.chats.listByUser,
    isAuthenticated && token ? { token } : "skip"
  );

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

  if (!isAuthenticated) {
    return (
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        contentContainerStyle={{ padding: theme.spacing.lg }}
      >
        <View
          style={{
            alignItems: "center",
            justifyContent: "center",
            paddingVertical: 60,
          }}
        >
          <Text style={{ fontSize: 48, marginBottom: 16 }}>
            {"\uD83D\uDCAC"}
          </Text>
          <Text
            style={{
              fontSize: 18,
              fontWeight: "600",
              color: theme.colors.text,
              marginBottom: 8,
            }}
          >
            Чатови
          </Text>
          <Text
            selectable
            style={{
              color: theme.colors.textSecondary,
              textAlign: "center",
              marginBottom: 24,
            }}
          >
            Најавете се за да ги видите вашите разговори.
          </Text>
          <Button onPress={() => router.push("/(auth)/login")}>
            Најави се
          </Button>
        </View>
      </ScrollView>
    );
  }

  if (chats === undefined) {
    return (
      <View
        style={{
          flex: 1,
          justifyContent: "center",
          alignItems: "center",
          backgroundColor: theme.colors.background,
        }}
      >
        <Loading />
      </View>
    );
  }

  if (chats.length === 0) {
    return (
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        contentContainerStyle={{ padding: theme.spacing.lg }}
      >
        <View
          style={{
            alignItems: "center",
            justifyContent: "center",
            paddingVertical: 60,
          }}
        >
          <Text style={{ fontSize: 48, marginBottom: 16 }}>
            {"\uD83D\uDCAC"}
          </Text>
          <Text
            style={{
              fontSize: 18,
              fontWeight: "600",
              color: theme.colors.text,
              marginBottom: 8,
            }}
          >
            Немате разговори
          </Text>
          <Text selectable style={{ color: theme.colors.textSecondary, textAlign: "center" }}>
            Започнете разговор со мајстор или клиент.
          </Text>
        </View>
      </ScrollView>
    );
  }

  return (
    <ScrollView
      contentInsetAdjustmentBehavior="automatic"
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
      }
      style={{ backgroundColor: theme.colors.background }}
    >
      {chats.map((chat) => (
        <ChatListItem key={chat._id} chat={chat} currentUserId={userId!} />
      ))}
    </ScrollView>
  );
}