import BackButtonTitle from "@/components/ui/BackButtonTitle";
import Button from "@/components/ui/Button";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { router } from "expo-router";
import moment from "moment";
import { CaretRight, Clock, ClockIcon, HeadsetIcon, PlusIcon } from "phosphor-react-native";
import { useEffect, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Pressable, Text, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

export default function Support() {
  const { primary } = useColor();
  const [page, setPage] = useState<number>(1);
  const [items, setItems] = useState<any[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const loadingMoreRef = useRef(false);

  const { data: response, isFetching } = useGetQuery({
    url: `/client/support-tickets`,
    params: { page },
    queryKey: "support-tickets",
  });

  useEffect(() => {
    if (response?.data) {
      if (page === 1) {
        setItems(response.data); // reset on first load
      } else {
        setItems((prev) => [...prev, ...response.data]);
      }
      setHasMore(!!response.next_page_url);
      loadingMoreRef.current = false; // reset lock
    }
  }, [response, page]);

  // append data when new page is fetched

  const loadMore = () => {
    if (!isFetching && hasMore && !loadingMoreRef.current) {
      loadingMoreRef.current = true; // lock to prevent double fire
      setPage((prev) => prev + 1);
    }
  };
  return (
    <SafeAreaView className="bg-white h-full">
      <FlatList
        data={items}
        keyExtractor={(_, idx) => idx.toString()}
        showsVerticalScrollIndicator={false}
        onEndReached={loadMore}
        contentContainerStyle={{ paddingBottom: 40 }}
        ListHeaderComponent={
          <View className="px-4">
            <View className="py-2">
              <BackButtonTitle title="Support" />
            </View>

            <View className="mt-8 mb-6 p-6 rounded-3xl" style={{ backgroundColor: primary[5] }}>
              <View className="flex-row items-center gap-2">
                <View className="size-14 rounded-2xl justify-center items-center shadow-sm" style={{ backgroundColor: "white" }}>
                  <HeadsetIcon size={32} color={primary.base} weight="duotone" />
                </View>
                <Text className="text-3xl font-manrope-extrabold text-slate-900">Get in Touch</Text>
              </View>
              <Text className="text-slate-500 w-[95%] pt-2 text-lg font-manrope-medium">Send us a message and we&apos;ll get back to you as soon as possible.</Text>

              <Button onPress={() => router.push("/support/create-ticket")} className="mt-6" text="Create Ticket" leftIcon={<PlusIcon size={20} color="white" weight="bold" />} />
            </View>

            {items.length > 0 && <Text className="text-slate-900 font-manrope-bold text-xl mb-4">Your Tickets</Text>}

            {items.length === 0 && !isFetching ? (
              <View className="py-20 items-center justify-center">
                <View className="size-20 bg-slate-50 rounded-full items-center justify-center mb-4">
                  <ClockIcon size={40} color="#cbd5e1" weight="light" />
                </View>
                <Text className="text-slate-400 font-manrope-semibold text-lg">No support tickets found</Text>
                <Text className="text-slate-400 font-manrope-medium text-sm text-center px-10 mt-1">When you create a ticket, it will appear here.</Text>
              </View>
            ) : null}
          </View>
        }
        renderItem={({ item, index }) => {
          const statusColors: any = {
            open: { bg: "#f0fdf4", text: "#16a34a", dot: "#22c55e" },
            closed: { bg: "#fef2f2", text: "#dc2626", dot: "#ef4444" },
            pending: { bg: "#fffbeb", text: "#d97706", dot: "#f59e0b" },
          };
          const status = statusColors[item?.status?.toLowerCase()] || { bg: "#f8fafc", text: "#64748b", dot: "#94a3b8" };

          const priorityColors: any = {
            high: { bg: "#fee2e2", text: "#ef4444" },
            medium: { bg: "#fef3c7", text: "#f59e0b" },
            low: { bg: "#dcfce7", text: "#22c55e" },
          };
          const priority = priorityColors[item?.priority?.toLowerCase()] || { bg: "#f1f5f9", text: "#475569" };

          return (
            <Pressable
              onPress={() => router.push(`/support/details?tkt_id=${item?.ticket_no}`)}
              className="p-5 rounded-3xl border mx-4 mb-4 bg-white shadow-sm border-slate-100 flex-col overflow-hidden"
              style={{
                borderLeftWidth: 6,
                borderLeftColor: primary.base,
              }}
            >
              <View className="flex-row justify-between items-start mb-3">
                <View>
                  <Text className="text-slate-400 font-manrope-bold text-xs uppercase tracking-wider">Ticket #{item?.ticket_no}</Text>
                  <Text className="font-manrope-bold text-lg text-slate-900 mt-1 leading-tight max-w-[85%]" numberOfLines={2}>
                    {item.subject}
                  </Text>
                </View>

                <View className="px-3 py-1.5 rounded-full" style={{ backgroundColor: priority.bg }}>
                  <Text className="text-[10px] uppercase font-manrope-extrabold" style={{ color: priority.text }}>
                    {item?.priority}
                  </Text>
                </View>
              </View>

              <View className="h-px bg-slate-50 w-full my-3" />

              <View className="flex-row justify-between items-center">
                <View className="flex-row items-center gap-2">
                  <View style={{ backgroundColor: status.bg }} className="flex-row items-center px-3 py-1.5 rounded-full gap-x-1.5">
                    <View className="size-1.5 rounded-full" style={{ backgroundColor: status.dot }} />
                    <Text className="text-xs font-manrope-bold capitalize" style={{ color: status.text }}>
                      {item?.status}
                    </Text>
                  </View>

                  <View className="flex-row items-center gap-1 ml-1">
                    <Clock size={12} color="#94a3b8" />
                    <Text className="text-slate-400 font-manrope-medium text-xs">{moment(item?.created_at).format("DD MMM, YYYY")}</Text>
                  </View>
                </View>

                <View className="size-8 rounded-full bg-slate-50 items-center justify-center">
                  <CaretRight size={16} color="#64748b" weight="bold" />
                </View>
              </View>
            </Pressable>
          );
        }}
        onEndReachedThreshold={0.5}
        ListFooterComponent={
          isFetching ? (
            <ActivityIndicator style={{ margin: 16 }} color={primary.base} />
          ) : !hasMore && items.length > 0 ? (
            <View className="py-10 items-center">
              <View className="w-1.5 h-1.5 rounded-full bg-slate-200" />
            </View>
          ) : null
        }
      />
    </SafeAreaView>
  );
}
