import { useNoticesStore } from "@/store/noticesStore";
import { NoticeCard } from "@/components/NoticeCard";
import { Button, ButtonText } from "@/components/ui/button";

import { Box } from "@/components/ui/box";
import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack";
import { ActivityIndicator, FlatList } from "react-native";
import { useEffect, useState, useRef } from "react";
import { createOrder, createPayment, getOrder } from "@/api/order";
import { Linking } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useToast, Toast, ToastTitle } from "@/components/ui/toast";
import { AppState } from "react-native";
import { useAuthStore } from "@/store/authStore";

export default function UserNotices() {
  const { notices, fetchNotices, deleteNotice } = useNoticesStore();
  const [isLoading, setIsLoading] = useState(true);
  const [isRedirecting, setIsRedirecting] = useState(false);
  const toast = useToast();
  const appState = useRef(AppState.currentState);
  const [toastId, setToastId] = useState(0);
  const { user_id } = useAuthStore.getState();
  const currentUserId = user_id;
  const [orderId, setOrderId] = useState(null);

  useEffect(() => {
    if (!isRedirecting) return;
    const subscription = AppState.addEventListener("change", (state) => {
      if (state === "active") {
        (async () => {
          const lastOrder = await getOrder(orderId);
          const lastPayments = lastOrder.payments;
          const paymentStatus =
            lastPayments.length > 0
              ? lastPayments[lastPayments.length - 1].status
              : null;
          setIsRedirecting(false);
          if (paymentStatus === "INCORRECT") {
            showNewToast("Płatność została anulowana.");
          } else if (paymentStatus === "CORRECT") {
            showNewToast("Płatność została zrealizowana.");
          } else {
            showNewToast("Płatność jeszcze nie wpłynęła.");
          }
        })();
      }
      appState.current = state;
    });
    return () => subscription.remove();
  }, [isRedirecting, toast, orderId]);

  useEffect(() => {
    const loadNotices = async () => {
      setIsLoading(true);
      try {
        await fetchNotices();
      } catch (err) {
        console.error("Błąd podczas pobierania ogłoszeń:", err);
      } finally {
        setIsLoading(false);
      }
    };
    loadNotices();
  }, [fetchNotices]);

  const showNewToast = (title) => {
    const newId = Math.random();
    setToastId(newId);
    toast.show({
      id: newId,
      placement: "top",
      duration: 3000,
      render: ({ id }) => {
        const uniqueToastId = "toast-" + id;
        return (
          <Toast nativeID={uniqueToastId} action="muted" variant="solid">
            <ToastTitle>{title}</ToastTitle>
          </Toast>
        );
      },
    });
  };

  const handleOrder = async (noticeId, type) => {
    {
      try {
        const result = await createOrder(noticeId, type);
        if (result) {
          setOrderId(result);
          try {
            const paymentResult = await createPayment(result);
            if (paymentResult) {
              setIsRedirecting(true);
              await Linking.openURL(paymentResult);
            } else {
              console.log(`Nie udało się aktywować ogłoszenia 4 ${noticeId}.`);
            }
          } catch (err) {
            // console.log("Błąd podczas aktywacji ogłoszenia 3:", err);
          }
        } else {
          // console.log(`Nie udało się aktywować ogłoszenia 2 ${noticeId}.`);
        }
      } catch (err) {
        console.log("Błąd podczas aktywacji ogłoszenia 1:", err);
      }
    }
  };

  const handleDeleteNotice = async (noticeId) => {
    try {
      await deleteNotice(noticeId);
    } catch (err) {
      console.error("Błąd podczas usuwania ogłoszenia:", err);
    }
  };

  const userNotices = notices
    .filter((notice) => notice.clientId === currentUserId)
    .sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate));

  if (isLoading) {
    return (
      <Box className="items-center justify-center flex-1">
        <ActivityIndicator size="large" color="#787878" />
      </Box>
    );
  }

  return (
    <VStack className="p-2">
      {isRedirecting && (
        <Box className="absolute inset-0 bg-white bg-opacity-30 justify-center items-center z-50">
          <Ionicons name="card-outline" size="30" className="pt-4" />
          <Text className="text-lg font-bold pt-2">
            Przekierowanie do płatności...
          </Text>
        </Box>
      )}
      {/* <Text className="text-2xl font-bold mb-4">Moje ogłoszenia</Text> */}
      {userNotices.length > 0 ? (
        <FlatList
          data={userNotices}
          renderItem={({ item }) => (
            <Box className="flex-1 mb-4 pb-2 bg-white rounded-lg">
              <NoticeCard notice={item} />
              <Box className="flex-row justify-between mt-2">
                <Button
                  className="ml-2"
                  onPress={() => handleDeleteNotice(item.noticeId)}
                  size="md"
                  variant="outline"
                  action="primary"
                >
                  <ButtonText>Usuń</ButtonText>
                  <Ionicons name="trash-outline" size={14} />
                </Button>

                {item.status === "ACTIVE" ? (
                  <Button
                    className="mr-2"
                    size="md"
                    variant="solid"
                    action="primary"
                    onPress={() => handleOrder(item.noticeId, "BOOST")}
                  >
                    <ButtonText>Podbij</ButtonText>
                    <Ionicons name="arrow-up" size={14} color="#fff" />
                  </Button>
                ) : (
                  <Button
                    className="mr-2"
                    size="md"
                    variant="solid"
                    action="primary"
                    onPress={() => handleOrder(item.noticeId, "ACTIVATION")}
                  >
                    <ButtonText>Aktywuj</ButtonText>
                    <Ionicons
                      name="arrow-redo-outline"
                      size={14}
                      color="#fff"
                    />
                  </Button>
                )}
              </Box>
            </Box>
          )}
          keyExtractor={(item) => item.noticeId.toString()}
        />
      ) : (
        <Text>Nie masz żadnych ogłoszeń.</Text>
      )}
    </VStack>
  );
}
