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 { 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 (
      <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="chatbubbles" 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>
    );
  }

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

      {chats.length === 0 ? (
        <ScrollView
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
          }
          contentContainerStyle={{ flex: 1, alignItems: "center", justifyContent: "center", padding: theme.spacing.lg }}
        >
          <View
            style={{
              width: 72,
              height: 72,
              borderRadius: 36,
              backgroundColor: theme.colors.surfaceAlt,
              alignItems: "center",
              justifyContent: "center",
              marginBottom: theme.spacing.md,
              ...theme.shadows.xs,
            }}
          >
            <Ionicons name="chatbubbles" size={30} color={theme.colors.textTertiary} />
          </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>
        </ScrollView>
      ) : (
        <ScrollView
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
          }
          style={{ backgroundColor: theme.colors.background }}
          contentContainerStyle={{ paddingBottom: 100 }}
        >
          {chats.map((chat) => (
            <ChatListItem key={chat._id} chat={chat} currentUserId={userId!} />
          ))}
        </ScrollView>
      )}
    </View>
  );
}
