import { View, Text, Pressable, ScrollView, RefreshControl, Alert } from "react-native";
import { useRouter } from "expo-router";
import { useState, useCallback } from "react";
import { useQuery, useMutation, usePaginatedQuery } from "convex/react";
import { api } from "../../../convex/_generated/api";
import { useAuth } from "../../_layout";
import { useTheme } from "../../../components/theme";
import { Button } from "../../../components/ui/button";
import { Badge } from "../../../components/ui/badge";
import { Loading } from "../../../components/ui/loading";
import { Card } from "../../../components/ui/card";
import { Avatar } from "../../../components/ui/avatar";
import { AdCard } from "../../../components/ad-card";
import { PostCard } from "../../../components/post-card";

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

  const user = useQuery(api.users.getCurrentUser, isAuthenticated ? { token: token! } : "skip");
  const myAdsResult = usePaginatedQuery(
    api.ads.getByHandymanPaginated,
    isAuthenticated && userId ? { handymanId: userId as any } : "skip",
    { initialNumItems: 20 }
  );
  const myPostsResult = usePaginatedQuery(
    api.posts.getByCustomerPaginated,
    isAuthenticated && userId ? { customerId: userId as any } : "skip",
    { initialNumItems: 20 }
  );
  const deleteAd = useMutation(api.ads.remove);
  const logoutMutation = useMutation(api.auth.logout);

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

  async function handleLogout() {
    if (token) {
      try {
        await logoutMutation({ token });
      } catch {}
    }
    await logout();
    router.replace("/(auth)/login");
  }

  async function handleDeleteAd(adId: string) {
    Alert.alert(
      "Избриши оглас",
      "Дали сте сигурни дека сакате да го избришете овој оглас?",
      [
        { text: "Откажи", style: "cancel" },
        {
          text: "Избриши",
          style: "destructive",
          onPress: async () => {
            try {
              await deleteAd({ token: token!, adId: adId as any });
            } catch (e: any) {
              Alert.alert("Грешка", e.message || "Неуспешно бришење");
            }
          },
        },
      ]
    );
  }

  if (!isAuthenticated) {
    return (
      <View style={{
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: theme.colors.background,
        padding: theme.spacing.lg,
      }}>
        <Text style={{ fontSize: 64, marginBottom: theme.spacing.md }}>👤</Text>
        <Text style={{ ...theme.typography.h2, color: theme.colors.text, marginBottom: theme.spacing.sm }}>
          Најавете се
        </Text>
        <Text selectable style={{ ...theme.typography.body, color: theme.colors.textSecondary, textAlign: "center", marginBottom: theme.spacing.lg }}>
          За да ги видите вашиот профил и податоци.
        </Text>
        <Button onPress={() => router.push("/(auth)/login")} size="lg">
          Најави се
        </Button>
      </View>
    );
  }

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

  const isHandyman = user.role === "handyman";
  const myAds = myAdsResult.results;
  const myPosts = myPostsResult.results;

  return (
    <ScrollView
      contentInsetAdjustmentBehavior="automatic"
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
      }
      contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md, paddingBottom: 80 }}
    >
      <Card variant="elevated" style={{ alignItems: "center", paddingVertical: theme.spacing.xl }}>
        <Avatar uri={user.avatarId ?? null} name={user.name || "Корисник"} size={80} />
        <Text selectable style={{ ...theme.typography.h2, color: theme.colors.text, marginTop: theme.spacing.md }}>
          {user.name || "Корисник"}
        </Text>
        <Badge label={isHandyman ? "Мајстор" : "Клиент"} variant={isHandyman ? "primary" : "default"} />
        {user.email && (
          <Text selectable style={{ ...theme.typography.body, color: theme.colors.textSecondary, marginTop: theme.spacing.sm }}>
            {user.email}
          </Text>
        )}
        {user.phone && (
          <Text selectable style={{ ...theme.typography.body, color: theme.colors.textSecondary }}>
            {user.phone}
          </Text>
        )}
      </Card>

      {isHandyman && (
        <>
          <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
            <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>
              Мои огласи
            </Text>
            <Button
              size="sm"
              onPress={() => router.push("/ad/create" as any)}
              accessibilityLabel="Креирај нов оглас"
            >
              + Нов оглас
            </Button>
          </View>

          {myAdsResult.status === "LoadingFirstPage" ? (
            <Loading />
          ) : myAds.length === 0 ? (
            <Card style={{ alignItems: "center", paddingVertical: theme.spacing.xl }}>
              <Text style={{ fontSize: 48, marginBottom: theme.spacing.sm }}>📋</Text>
              <Text selectable style={{ ...theme.typography.body, color: theme.colors.textSecondary, textAlign: "center" }}>
                Сè уште немате огласи.
              </Text>
              <Button
                variant="outline"
                size="sm"
                onPress={() => router.push("/ad/create" as any)}
                style={{ marginTop: theme.spacing.md }}
              >
                Креирај оглас
              </Button>
            </Card>
          ) : (
            <View style={{ gap: theme.spacing.sm }}>
              {myAds.map((ad) => (
                <View key={ad._id} style={{ gap: theme.spacing.sm }}>
                  <AdCard ad={ad} />
                  <View style={{ flexDirection: "row", gap: theme.spacing.sm }}>
                    <Pressable
                      accessible
                      accessibilityLabel={`Уреди оглас: ${ad.title}`}
                      accessibilityRole="button"
                      onPress={() => router.push(`/ad/create?editId=${ad._id}` as any)}
                      style={{
                        flex: 1,
                        backgroundColor: theme.colors.surface,
                        borderRadius: theme.radius.md,
                        paddingVertical: 10,
                        alignItems: "center",
                        borderWidth: 1,
                        borderColor: theme.colors.borderLight,
                      }}
                    >
                      <Text style={{ color: theme.colors.primary, fontWeight: "600", fontSize: 14 }}>Уреди</Text>
                    </Pressable>
                    <Pressable
                      accessible
                      accessibilityLabel={`Избриши оглас: ${ad.title}`}
                      accessibilityRole="button"
                      onPress={() => handleDeleteAd(ad._id)}
                      style={{
                        flex: 1,
                        backgroundColor: theme.colors.errorLight,
                        borderRadius: theme.radius.md,
                        paddingVertical: 10,
                        alignItems: "center",
                      }}
                    >
                      <Text style={{ color: theme.colors.error, fontWeight: "600", fontSize: 14 }}>Избриши</Text>
                    </Pressable>
                  </View>
                </View>
              ))}
            </View>
          )}

          {myAdsResult.status === "CanLoadMore" && (
            <Pressable
              accessible
              accessibilityLabel="Вчитај повеќе огласи"
              accessibilityRole="button"
              onPress={() => myAdsResult.loadMore(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>
          )}
        </>
      )}

      {!isHandyman && (
        <>
          <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
            <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>
              Мои побарувања
            </Text>
            <Button
              size="sm"
              onPress={() => router.push("/post/create" as any)}
              accessibilityLabel="Креирај ново побарување"
            >
              + Ново
            </Button>
          </View>

          {myPostsResult.status === "LoadingFirstPage" ? (
            <Loading />
          ) : myPosts.length === 0 ? (
            <Card style={{ alignItems: "center", paddingVertical: theme.spacing.xl }}>
              <Text style={{ fontSize: 48, marginBottom: theme.spacing.sm }}>📝</Text>
              <Text selectable style={{ ...theme.typography.body, color: theme.colors.textSecondary, textAlign: "center" }}>
                Сè уште немате побарувања.
              </Text>
              <Button
                variant="outline"
                size="sm"
                onPress={() => router.push("/post/create" as any)}
                style={{ marginTop: theme.spacing.md }}
              >
                Креирај побарување
              </Button>
            </Card>
          ) : (
            <View style={{ gap: theme.spacing.sm }}>
              {myPosts.map((post) => (
                <PostCard key={post._id} post={post} />
              ))}
            </View>
          )}

          {myPostsResult.status === "CanLoadMore" && (
            <Pressable
              accessible
              accessibilityLabel="Вчитај повеќе побарувања"
              accessibilityRole="button"
              onPress={() => myPostsResult.loadMore(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>
          )}
        </>
      )}

      <Card>
        <Pressable
          accessible
          accessibilityLabel="Поставки"
          accessibilityRole="button"
          style={{ paddingVertical: theme.spacing.sm }}
        >
          <Text style={{ ...theme.typography.body, color: theme.colors.text }}>Поставки</Text>
        </Pressable>
        <View style={{ height: 1, backgroundColor: theme.colors.borderLight, marginVertical: theme.spacing.xs }} />
        <Pressable
          accessible
          accessibilityLabel="Оцени"
          accessibilityRole="button"
          style={{ paddingVertical: theme.spacing.sm }}
        >
          <Text style={{ ...theme.typography.body, color: theme.colors.text }}>Оцени ја апликацијата</Text>
        </Pressable>
      </Card>

      <Button variant="destructive" onPress={handleLogout} fullWidth>
        Одјави се
      </Button>
    </ScrollView>
  );
}
