import { globalRole, keyWibu, TEMA } from "@/module/_global";
import LayoutModal from "@/module/_global/layout/layout_modal";
import { useHookstate } from "@hookstate/core";
import { Box, Flex, SimpleGrid, Stack, Text } from "@mantine/core";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import toast from "react-hot-toast";
import { BiArchive } from "react-icons/bi";
import { FaCheck, FaPencil, FaUsers } from "react-icons/fa6";
import { MdClose } from "react-icons/md";
import { useWibuRealtime } from "wibu-realtime";
import { funDeleteDiscussionGeneral, funEditStatusDiscussionGeneral } from "../lib/api_discussion_general";
import { globalRefreshDiscussionGeneral } from "../lib/val_discussion_general";

export default function DrawerDetailDiscussionGeneral({ onSuccess, id, status, active }: { onSuccess: (val: boolean) => void, id: string, status: number, active: boolean }) {
   const [isValModal, setValModal] = useState(false)
   const [isValModalStatus, setValModalStatus] = useState(false)
   const router = useRouter()
   const param = useParams<{ id: string, detail: string }>()
   const roleLogin = useHookstate(globalRole)
   const refresh = useHookstate(globalRefreshDiscussionGeneral)
   const tema = useHookstate(TEMA)
   const [dataRealTime, setDataRealtime] = useWibuRealtime({
      WIBU_REALTIME_TOKEN: keyWibu,
      project: "sdm"
   })
   const [loadingUpdate, setLoadingUpdate] = useState(false)
   const [loadingDelete, setLoadingDelete] = useState(false)


   async function fetchStatusDiscussion(val: boolean) {
      try {
         setLoadingUpdate(true)
         if (val) {
            const response = await funEditStatusDiscussionGeneral(id, { status: status })
            if (response.success) {
               toast.success(response.message)
               refresh.set(!refresh.get())
               setDataRealtime([{
                  category: "discussion-general-detail",
                  id: id,
               }])
               onSuccess(false)
            } else {
               toast.error(response.message)
            }
         }
      } catch (error) {
         console.error(error);
         toast.error("Gagal mengupdate diskusi umum, coba lagi nanti");
      } finally {
         setLoadingUpdate(false)
         setValModalStatus(false)
      }
   }

   async function fetchDeleteDiscussion(val: boolean) {
      try {
         if (val) {
            setLoadingDelete(true)
            const response = await funDeleteDiscussionGeneral(id, { active: !active })
            if (response.success) {
               toast.success(response.message)
               onSuccess(false)
               if (active) {
                  setDataRealtime([
                     {
                        category: "discussion-general-delete",
                        id: id,
                        user: response.user
                     },
                     {
                        category: "discussion-general",
                     }
                  ])
                  router.push(`/discussion`)
               } else {
                  refresh.set(!refresh.get())
                  setDataRealtime([
                     {
                        category: "discussion-general-detail",
                        id: id,
                     },
                     {
                        category: "discussion-general",
                     }
                  ])
               }

            } else {
               toast.error(response.message)
            }
         }
      } catch (error) {
         console.error(error);
         toast.error("Gagal mengupdate diskusi umum, coba lagi nanti");
      } finally {
         setLoadingDelete(false)
         setValModal(false)
      }
   }


   return (
      <Box>
         <Stack pt={10}>
            <SimpleGrid
               cols={{ base: 3, sm: 3, lg: 3 }}
               spacing={{ base: 'xl', sm: 'xl' }}
               verticalSpacing={{ base: 'xl', sm: 'xl' }}
            >

               <Flex onClick={() => window.location.href = `/discussion/${param.id}/member/`} justify={'center'} align={'center'} direction={'column'} >
                  <Box>
                     <FaUsers size={30} color={tema.get().utama} />
                  </Box>
                  <Box>
                     <Text c={tema.get().utama}>Anggota</Text>
                  </Box>
               </Flex>

               {
                  (roleLogin.get() != "user" && roleLogin.get() != "coadmin") ? (
                     <>
                        {
                           active && (
                              <>
                                 <Flex onClick={() => window.location.href = `/discussion/${param.id}/edit/`} justify={'center'} align={'center'} direction={'column'} >
                                    <Box>
                                       <FaPencil size={30} color={tema.get().utama} />
                                    </Box>
                                    <Box>
                                       <Text c={tema.get().utama}>Edit</Text>
                                    </Box>
                                 </Flex>

                                 <Flex justify={'center'} align={'center'} direction={'column'} onClick={() => setValModalStatus(true)}  >
                                    {status === 1 ? (
                                       <>
                                          <Flex justify={'center'} align={'center'} direction={'column'}>
                                             <Box>
                                                <MdClose size={30} color={tema.get().utama} />
                                             </Box>
                                             <Text style={{ color: tema.get().utama }}>Tutup Diskusi</Text>
                                          </Flex>
                                       </>
                                    ) : (
                                       <>
                                          <Flex justify={'center'} align={'center'} direction={'column'}>

                                             <Box>
                                                <FaCheck size={30} color={tema.get().utama} />
                                             </Box>
                                             <Text style={{ color: tema.get().utama }}>Buka Diskusi</Text>
                                          </Flex>
                                       </>
                                    )}
                                 </Flex>
                              </>
                           )
                        }

                        <Flex onClick={() => setValModal(true)} justify={'center'} align={'center'} direction={'column'} >
                           <Box>
                              <BiArchive size={30} color={tema.get().utama} />
                           </Box>
                           <Box>
                              <Text c={tema.get().utama}>{active ? "Arsipkan" : "Aktifkan Diskusi"}</Text>
                           </Box>
                        </Flex>
                     </>
                  )
                     : (<></>)
               }

            </SimpleGrid>
         </Stack>

         <LayoutModal loading={loadingDelete} opened={isValModal} onClose={() => setValModal(false)}
            description={`Apakah Anda yakin ingin ${active ? "mengarsipkan" : "mengaktifkan"}  diskusi ini?`}
            onYes={(val) => {
               fetchDeleteDiscussion(val)
            }} />


         <LayoutModal loading={loadingUpdate} opened={isValModalStatus} onClose={() => setValModalStatus(false)}
            description="Apakah Anda yakin ingin mengubah status diskusi ini?"
            onYes={(val) => {
               fetchStatusDiscussion(val)
            }} />
      </Box>
   )
}