'use client'
import { NotificationCustome } from "@/module/_global";
import { useShallowEffect } from "@mantine/hooks";
import { useRouter } from "next/navigation";
import { useState } from "react";
import toast from "react-hot-toast";
import { funGetOneNotificationAnnouncement, funReadNotification } from "../lib/api_notification";
import { IListNotification } from "../lib/type_notification";

export default function NotificationAnnouncement() {
   const router = useRouter()
   const [tampilNotif, setTampilNotif] = useState(false)
   const [isData, setData] = useState<IListNotification[]>([]);

   async function fetchData() {
      try {
         const res = await funGetOneNotificationAnnouncement();
         if (res.show) {
            setTampilNotif(true)
            setData(res.data)
         }
      } catch (error) {
         console.error(error);
      } finally {
         setTimeout(() => {
            setTampilNotif(false);
         }, 6000);
      }
   }

   useShallowEffect(() => {
      fetchData();
   }, []);

   async function onClickNotif(category: string, idContent: string, idData: string) {
      try {
         const response = await funReadNotification({ id: idData });
         if (response.success) {
            router.push(`/${category}/${idContent}`);
         } else {
            toast.error(response.message);
         }
      } catch (error) {
         console.error(error);
         toast.error("Gagal memuat data, coba lagi nanti");
      }
   }

   return (
      <>
         {
            tampilNotif &&
            <NotificationCustome
               title={isData[0]?.title}
               desc={isData[0]?.desc}
               onClick={() => { onClickNotif(isData[0]?.category, isData[0]?.idContent, isData[0]?.id) }}
               onClose={() => { '' }}
            />
         }
      </>
   )
}