"use client"
import { TEMA } from '@/module/_global';
import { useHookstate } from '@hookstate/core';
import { Box, Flex, SimpleGrid, Stack, Text } from '@mantine/core';
import { useShallowEffect } from '@mantine/hooks';
import { useState } from 'react';
import toast from 'react-hot-toast';
import { LuCheckCheck } from 'react-icons/lu';
import { funGetHome } from '../lib/api_home';
import { funReadAllNotification } from '../lib/api_notification';
import { globalRefreshNotif } from '../lib/val_home';

export default function DrawerNotification({ onDone }: { onDone: () => void }) {
   const tema = useHookstate(TEMA)
   const reloadNotif = useHookstate(globalRefreshNotif)
   const [disabled, setDisabled] = useState(false)
   const [notif, setNotif] = useState(0)

   async function handleReadAll() {
      try {
         const res = await funReadAllNotification()
         if (res.success) {
            toast.success(res.message)
            reloadNotif.set(!reloadNotif.get())
         } else {
            toast.error(res.message)
         }
      } catch (error) {
         console.error(error)
         toast.error("Gagal mengupdate notifikasi, coba lagi nanti")
      } finally {
         onDone()
      }
   }

   const fetchData = async () => {
      try {
         setDisabled(true)
         const response = await funGetHome('?cat=header')
         if (response.success) {
            setNotif(response.data.totalNotif)
            if (response.data.totalNotif > 0) {
               setDisabled(false)
            }
         } else {
            toast.error(response.message);
         }
      } catch (error) {
         toast.error("Gagal mendapatkan data, coba lagi nanti");
         console.error(error);
      }
   };

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


   return (
      <Box>
         <Stack pt={10}>
            <SimpleGrid cols={{ base: 3, sm: 3, lg: 3 }} >
               <Flex onClick={() => { !disabled && handleReadAll() }} justify={'center'} align={'center'} direction={'column'} >
                  <Box>
                     <LuCheckCheck size={30} color={disabled ? 'gray' : tema.get().utama} />
                  </Box>
                  <Box>
                     <Text c={disabled ? 'gray' : tema.get().utama} ta={"center"}>Tandai Dibaca Semua</Text>
                  </Box>
               </Flex>
            </SimpleGrid>
         </Stack>
      </Box>
   );
}
