import { useState, useCallback } from "react";
import { View, Text, ScrollView, Pressable, Alert, RefreshControl } from "react-native";
import { useLocalSearchParams, Stack, useRouter } from "expo-router";
import { useQuery, useMutation } from "convex/react";
import { api } from "../../convex/_generated/api";
import { useAuth } from "../_layout";
import { useTheme } from "../../components/theme";
import { Badge } from "../../components/ui/badge";
import { Rating } from "../../components/ui/rating";
import { Button } from "../../components/ui/button";
import { Avatar } from "../../components/ui/avatar";
import { Loading } from "../../components/ui/loading";
import { Card } from "../../components/ui/card";
import { ReviewCard } from "../../components/review-card";
import { getCategoryName, CATEGORY_EMOJI } from "../../lib/constants";

export default function AdDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const theme = useTheme();
  const router = useRouter();
  const { token, isAuthenticated, userId } = useAuth();

  const ad = useQuery(api.ads.getById, id ? { id: id as any } : "skip");
  const handyman = useQuery(
    api.users.getById,
    ad ? { id: ad.handymanId } : "skip"
  );
  const reviews = useQuery(
    api.reviews.getByAd,
    id ? { adId: id as any } : "skip"
  );

  const reviewCustomerIds = reviews
    ? [...new Set(reviews.map((r) => r.customerId))]
    : [];
  const customer0 = useQuery(
    api.users.getById,
    reviewCustomerIds.length > 0 ? { id: reviewCustomerIds[0] as any } : "skip"
  );
  const customer1 = useQuery(
    api.users.getById,
    reviewCustomerIds.length > 1 ? { id: reviewCustomerIds[1] as any } : "skip"
  );
  const customer2 = useQuery(
    api.users.getById,
    reviewCustomerIds.length > 2 ? { id: reviewCustomerIds[2] as any } : "skip"
  );
  const customer3 = useQuery(
    api.users.getById,
    reviewCustomerIds.length > 3 ? { id: reviewCustomerIds[3] as any } : "skip"
  );
  const customer4 = useQuery(
    api.users.getById,
    reviewCustomerIds.length > 4 ? { id: reviewCustomerIds[4] as any } : "skip"
  );
  const customersById: Record<string, any> = {};
  if (customer0) customersById[reviewCustomerIds[0] as string] = customer0;
  if (customer1) customersById[reviewCustomerIds[1] as string] = customer1;
  if (customer2) customersById[reviewCustomerIds[2] as string] = customer2;
  if (customer3) customersById[reviewCustomerIds[3] as string] = customer3;
  if (customer4) customersById[reviewCustomerIds[4] as string] = customer4;

  const deleteAd = useMutation(api.ads.remove);
  const startChat = useMutation(api.chats.getOrCreate);
  const [startingChat, setStartingChat] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

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

  async function handleStartChat() {
    if (!token || !ad) return;
    setStartingChat(true);
    try {
      const chatId = await startChat({ token, partnerId: ad.handymanId });
      router.push(`/chat/${chatId}` as any);
    } catch (e: any) {
      Alert.alert("Грешка", e.message || "Неуспешно започнување разговор");
    } finally {
      setStartingChat(false);
    }
  }

  if (!ad) {
    return (
      <>
        <Stack.Screen options={{ title: "Оглас", headerShown: true, headerBackButtonDisplayMode: "minimal" }} />
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: theme.colors.background }}>
          <Loading />
        </View>
      </>
    );
  }

  const isOwner = userId === ad.handymanId;
  const categoryName = getCategoryName(ad.category);
  const categoryEmoji = CATEGORY_EMOJI[ad.category] || "📋";

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

  const existingUserReview = reviews?.find((r) => r.customerId === userId);

  return (
    <>
      <Stack.Screen
        options={{
          title: ad.title.length > 20 ? ad.title.slice(0, 20) + "…" : ad.title,
          headerShown: true,
          headerBackButtonDisplayMode: "minimal",
        }}
      />
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md, paddingBottom: 100 }}
      >
        <View
          accessible
          accessibilityLabel={`Слика за ${ad.title}`}
          style={{
            backgroundColor: theme.colors.surfaceAlt,
            borderRadius: theme.radius.lg,
            aspectRatio: 16 / 9,
            alignItems: "center",
            justifyContent: "center",
            borderWidth: 1,
            borderColor: theme.colors.borderLight,
            borderStyle: "dashed",
          }}
        >
          <View
            style={{
              width: 64,
              height: 64,
              borderRadius: 32,
              backgroundColor: theme.colors.primaryLight,
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Text style={{ fontSize: 32 }}>{categoryEmoji}</Text>
          </View>
          <Text style={{ ...theme.typography.caption, color: theme.colors.textTertiary, marginTop: theme.spacing.sm }}>
            Нема слики
          </Text>
        </View>

        <View style={{ gap: theme.spacing.xs }}>
          <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start" }}>
            <View style={{ flex: 1 }}>
              <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>{ad.title}</Text>
            </View>
            {ad.priceRange && (
              <View
                style={{
                  backgroundColor: theme.colors.primaryLight,
                  paddingHorizontal: 12,
                  paddingVertical: 6,
                  borderRadius: theme.radius.sm,
                  marginLeft: theme.spacing.sm,
                }}
              >
                <Text selectable style={{ fontSize: 15, fontWeight: "700", color: theme.colors.primaryDark }}>
                  {ad.priceRange}
                </Text>
              </View>
            )}
          </View>

          <View style={{ flexDirection: "row", alignItems: "center", gap: theme.spacing.sm, flexWrap: "wrap" }}>
            <Badge label={categoryName} variant="primary" />
            <Text selectable style={{ ...theme.typography.caption, color: theme.colors.textSecondary }}>
              📍 {ad.location}
            </Text>
          </View>

          {ad.ratingAvg != null && ad.ratingAvg > 0 && (
            <Rating value={ad.ratingAvg} count={ad.reviewCount} size={18} />
          )}
        </View>

        {ad.availability && (
          <Card>
            <Text style={{ ...theme.typography.captionBold, color: theme.colors.text, marginBottom: theme.spacing.xs }}>
              Расположивост
            </Text>
            <Text selectable style={{ ...theme.typography.body, color: theme.colors.textSecondary }}>
              {ad.availability}
            </Text>
          </Card>
        )}

        <Card>
          <Text style={{ ...theme.typography.captionBold, color: theme.colors.text, marginBottom: theme.spacing.xs }}>
            Опис
          </Text>
          <Text style={{ ...theme.typography.body, color: theme.colors.textSecondary, lineHeight: 22 }}>
            {ad.description}
          </Text>
        </Card>

        <Card>
          <Pressable
            accessible
            accessibilityLabel={`Профил на ${handyman?.name || "Мајстор"}`}
            accessibilityRole="link"
            onPress={() => {
              if (handyman) router.push(`/(tabs)/(profile)`);
            }}
            style={{ flexDirection: "row", alignItems: "center", gap: theme.spacing.md }}
          >
            <Avatar uri={handyman?.avatarId ?? null} name={handyman?.name || "Мајстор"} size={48} />
            <View style={{ flex: 1 }}>
              <Text style={{ ...theme.typography.bodyBold, color: theme.colors.text }}>
                {handyman?.name || "Мајстор"}
              </Text>
              <Text style={{ ...theme.typography.caption, color: theme.colors.textSecondary }}>
                Мајстор
              </Text>
            </View>
            <Text style={{ color: theme.colors.primary, fontSize: 20 }}>›</Text>
          </Pressable>
        </Card>

        {!isOwner && isAuthenticated && (
          <View style={{ gap: theme.spacing.sm }}>
            <Button loading={startingChat} onPress={handleStartChat} size="lg" fullWidth>
              Започни разговор
            </Button>
            {!existingUserReview && (
              <Button
                variant="outline"
                onPress={() => router.push(`/review/create?adId=${ad._id}` as any)}
                fullWidth
              >
                Напиши оценка
              </Button>
            )}
            {existingUserReview && (
              <Text style={{ ...theme.typography.caption, color: theme.colors.textTertiary, textAlign: "center" }}>
                Веќе напишавте оценка за овој оглас
              </Text>
            )}
          </View>
        )}

        {isOwner && (
          <View style={{ gap: theme.spacing.sm }}>
            <Button
              variant="outline"
              onPress={() => router.push(`/ad/create?editId=${ad._id}` as any)}
              fullWidth
            >
              Уреди оглас
            </Button>
            <Button variant="destructive" onPress={handleDelete} fullWidth>
              Избриши оглас
            </Button>
          </View>
        )}

        {!isOwner && !isAuthenticated && (
          <Card>
            <Text style={{ ...theme.typography.body, color: theme.colors.textSecondary, textAlign: "center" }}>
              Најавете се за да започнете разговор или да напишете оценка.
            </Text>
            <View style={{ marginTop: theme.spacing.md }}>
              <Button onPress={() => router.push("/(auth)/login")} fullWidth>
                Најави се
              </Button>
            </View>
          </Card>
        )}

        {reviews && reviews.length > 0 && (
          <View style={{ gap: theme.spacing.sm }}>
            <View style={{ flexDirection: "row", alignItems: "center", justifyContent: "space-between" }}>
              <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>
                Оцени
              </Text>
              <View style={{ flexDirection: "row", alignItems: "center", gap: theme.spacing.xs }}>
                <Text style={{ ...theme.typography.h2, color: theme.colors.text }}>
                  {ad.ratingAvg?.toFixed(1)}
                </Text>
                <Text style={{ ...theme.typography.caption, color: theme.colors.textTertiary }}>
                  ({ad.reviewCount} {ad.reviewCount === 1 ? "оценка" : "оцени"})
                </Text>
              </View>
            </View>

            {reviews.map((review) => {
              const customer = customersById[review.customerId as string];
              return (
                <ReviewCard
                  key={review._id}
                  review={review}
                  customerName={customer?.name || "Клиент"}
                  customerAvatarId={customer?.avatarId}
                />
              );
            })}
          </View>
        )}
      </ScrollView>
    </>
  );
}
