import { useState } from "react";
import { View, Text, ScrollView, Pressable, Alert } 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);

  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"
        contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md, paddingBottom: 100 }}
      >
        <View
          style={{
            backgroundColor: theme.colors.surface,
            borderRadius: theme.radius.lg,
            aspectRatio: 16 / 9,
            alignItems: "center",
            justifyContent: "center",
            borderWidth: 1,
            borderColor: theme.colors.border,
            borderStyle: "dashed",
          }}
        >
          <Text style={{ fontSize: 48 }}>{categoryEmoji}</Text>
          <Text style={{ color: theme.colors.textTertiary, marginTop: theme.spacing.sm, fontSize: 14 }}>
            Нема слики
          </Text>
        </View>

        <View>
          <Text style={{ fontSize: 22, fontWeight: "700", color: theme.colors.text }}>{ad.title}</Text>
          {ad.priceRange && (
            <Text style={{ fontSize: 18, fontWeight: "600", color: theme.colors.primary, marginTop: theme.spacing.xs }}>
              {ad.priceRange}
            </Text>
          )}
        </View>

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

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

        {ad.availability && (
          <Card>
            <Text style={{ fontSize: 14, fontWeight: "600", color: theme.colors.text, marginBottom: theme.spacing.xs }}>
              Расположивост
            </Text>
            <Text style={{ fontSize: 14, color: theme.colors.textSecondary }}>{ad.availability}</Text>
          </Card>
        )}

        <Card>
          <Text style={{ fontSize: 14, fontWeight: "600", color: theme.colors.text, marginBottom: theme.spacing.xs }}>
            Опис
          </Text>
          <Text style={{ fontSize: 15, color: theme.colors.textSecondary, lineHeight: 22 }}>{ad.description}</Text>
        </Card>

        <Card>
          <Pressable
            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={{ fontSize: 16, fontWeight: "600", color: theme.colors.text }}>
                {handyman?.name || "Мајстор"}
              </Text>
              <Text style={{ fontSize: 13, color: theme.colors.textSecondary }}>Мајстор</Text>
            </View>
          </Pressable>
        </Card>

        {!isOwner && isAuthenticated && (
          <View style={{ gap: theme.spacing.sm }}>
            <Button loading={startingChat} onPress={handleStartChat}>Започни разговор</Button>
            {!existingUserReview && (
              <Button variant="outline" onPress={() => router.push(`/review/create?adId=${ad._id}` as any)}>
                Напиши оценка
              </Button>
            )}
            {existingUserReview && (
              <Text style={{ fontSize: 13, 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)}
            >
              Уреди оглас
            </Button>
            <Button variant="destructive" onPress={handleDelete}>
              Избриши оглас
            </Button>
          </View>
        )}

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

        {/* Reviews section */}
        {reviews && reviews.length > 0 && (
          <View style={{ gap: theme.spacing.sm }}>
            <View style={{ flexDirection: "row", alignItems: "center", justifyContent: "space-between" }}>
              <Text style={{ fontSize: 18, fontWeight: "700", color: theme.colors.text }}>
                Оцени
              </Text>
              <View style={{ flexDirection: "row", alignItems: "center", gap: theme.spacing.xs }}>
                <Text style={{ fontSize: 22, fontWeight: "700", color: theme.colors.text }}>
                  {ad.ratingAvg?.toFixed(1)}
                </Text>
                <Text style={{ fontSize: 14, 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>
    </>
  );
}