import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useTranslations } from "@/providers/TranslationProviders";
import { formatDateTime } from "@/utils/helper";
import { useLocalSearchParams } from "expo-router";
import moment from "moment";
import { useEffect } from "react";
import {
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Text,
  View,
  ActivityIndicator,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import FilePreview from "../FilePreview";
import Replies from "./Replies";
import ReplyTicket from "./ReplyTicket";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import { useColor } from "@/hooks/useColor";
import { ChatCircleDots, CalendarBlank, Hash } from "phosphor-react-native";

export default function Details() {
  const { tkt_id } = useLocalSearchParams();
  const { tran } = useTranslations();
  const { primary } = useColor();
  const {
    data: ticket,
    isLoading,
    refetch,
    isFetching,
  } = useGetQuery({
    url: `/client/support-tickets/${tkt_id}/replies`,
    queryKey: "support-tickets",
    enabled: !!tkt_id,
  });

  useEffect(() => {
    refetch();
  }, [tkt_id, refetch]);

  const messages =
    ticket?.replies?.map((reply: any) => ({
      id: reply.id,
      sender: reply.replier?.full_name || "Unknown",
      time: formatDateTime(reply.created_at),
      text: reply.message,
      isMyMessage: reply.user_type === "User",
      attachments: reply.attachments || [],
    })) ?? [];

  const firstMessage = messages.length > 0 ? messages[0] : null;
  const remainingReplies = messages.length > 1 ? messages.slice(1) : [];

  if (isLoading && !ticket) {
    return (
      <SafeAreaView className="bg-white h-full justify-center items-center">
        <ActivityIndicator size="large" color={primary.base} />
      </SafeAreaView>
    );
  }



  return (
    <SafeAreaView className="bg-white h-full">
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={{ flex: 1 }}
        enabled={true}
      >
        <View className="px-4 py-2">
          <BackButtonTitle title="Ticket Details" />
        </View>

        <ScrollView
          className="flex-1"
          contentContainerStyle={{ flexGrow: 1, paddingBottom: 60 }}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          <View className="px-4 mt-6">
            <View className="p-5 rounded-3xl bg-slate-50 border border-slate-100 mb-6">
              <View className="flex-row items-center justify-between mb-4">
                <View className="flex-row items-center gap-x-2 bg-white px-3 py-1.5 rounded-full border border-slate-100">
                  <Hash size={16} color="#64748b" weight="bold" />
                  <Text className="font-manrope-bold text-slate-600">
                    {tkt_id}
                  </Text>
                </View>
                <View className="flex-row items-center gap-x-2">
                  <CalendarBlank size={16} color="#64748b" />
                  <Text className="text-slate-500 font-manrope-medium">
                    {moment(ticket?.created_at).format("DD MMM, YYYY")}
                  </Text>
                </View>
              </View>
              <Text className="text-2xl font-manrope-extrabold text-slate-900 leading-8">
                {ticket?.subject || "Support Request"}
              </Text>
            </View>

            {firstMessage && (
              <View className="mb-10">
                <View className="flex-row items-center gap-x-2 mb-4">
                  <View
                    className="size-8 rounded-full items-center justify-center"
                    style={{ backgroundColor: primary[5] }}
                  >
                    <ChatCircleDots
                      size={18}
                      color={primary.base}
                      weight="duotone"
                    />
                  </View>
                  <Text className="font-manrope-bold text-lg text-slate-800">
                    Initial Message
                  </Text>
                </View>

                <View className="p-5 rounded-2xl bg-white border border-slate-100 shadow-sm">
                  <Text className="text-lg text-slate-700 font-manrope-regular leading-7">
                    {firstMessage.text}
                  </Text>

                  {ticket?.attachments && ticket.attachments.length > 0 && (
                    <View className="mt-6 pt-6 border-t border-slate-50">
                      <Text className="text-sm font-manrope-bold text-slate-400 uppercase tracking-widest mb-3">
                        {tran("Attachments")}
                      </Text>
                      <View className="flex-row flex-wrap gap-3">
                        {ticket.attachments.map(
                          (item: string, index: number) => (
                            <FilePreview
                              key={index}
                              item={item}
                              index={index}
                            />
                          ),
                        )}
                      </View>
                    </View>
                  )}
                </View>
              </View>
            )}

            <Replies tran={tran} replies={remainingReplies} />

            <View className="mt-8">
              <ReplyTicket ticketNumber={`${tkt_id}`} refetch={refetch} />
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}
