'use client'
import NotificationCustomeCenter from "@/module/_global/components/notification_custome_center";
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);
      }
   }

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

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


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