'use client'
import { urlCompleted } from '@/lib/urlCompleted';
import { globalRole, keyWibu, LayoutDrawer, TEMA } from '@/module/_global';
import LayoutModal from '@/module/_global/layout/layout_modal';
import { globalIsMemberDivision } from '@/module/division_new';
import { useHookstate } from '@hookstate/core';
import { Box, Flex, Grid, Group, SimpleGrid, Stack, Text } from '@mantine/core';
import { useMediaQuery, useShallowEffect } from '@mantine/hooks';
import { useParams } from 'next/navigation';
import { useState } from 'react';
import toast from 'react-hot-toast';
import { FaTrash } from 'react-icons/fa6';
import { LuLink } from 'react-icons/lu';
import { RiExternalLinkLine } from 'react-icons/ri';
import { useWibuRealtime } from 'wibu-realtime';
import { funDeleteLinkTask, funGetTaskDivisionById } from '../lib/api_task';
import { IDataLinkTaskDivision } from '../lib/type_task';

export default function ListLinkDetailTask() {
   const isMobile = useMediaQuery("(max-width: 350px)");
   const roleLogin = useHookstate(globalRole)
   const memberDivision = useHookstate(globalIsMemberDivision)
   const [isData, setData] = useState<IDataLinkTaskDivision[]>([])
   const [loading, setLoading] = useState(true)
   const param = useParams<{ id: string, detail: string }>()
   const [openDrawer, setOpenDrawer] = useState(false)
   const [isOpenModal, setOpenModal] = useState(false)
   const [loadingModal, setLoadingModal] = useState(false)
   const [linkData, setLinkData] = useState('')
   const [idData, setIdData] = useState('')
   const tema = useHookstate(TEMA)
   const [reason, setReason] = useState("")
   const [dataRealTime, setDataRealtime] = useWibuRealtime({
      WIBU_REALTIME_TOKEN: keyWibu,
      project: "sdm"
   })


   async function getOneDataCancel() {
      try {
         const res = await funGetTaskDivisionById(param.detail, 'data');
         if (res.success) {
            setReason(res.data.reason);
         } else {
            toast.error(res.message);
         }

      } catch (error) {
         console.error(error);
         toast.error("Gagal mendapatkan data tugas divisi, coba lagi nanti");
      }
   }

   useShallowEffect(() => {
      getOneDataCancel();
   }, [param.detail])

   async function getOneData(loading: boolean) {
      try {
         setLoading(loading)
         const res = await funGetTaskDivisionById(param.detail, 'link');
         if (res.success) {
            setData(res.data)
         } else {
            toast.error(res.message);
         }
      } catch (error) {
         console.error(error);
         toast.error("Gagal mendapatkan file tugas divisi, coba lagi nanti");
      } finally {
         setLoading(false)
      }
   }

   useShallowEffect(() => {
      getOneData(true);
   }, [param.detail])


   async function onDelete() {
      try {
         setLoadingModal(true)
         const res = await funDeleteLinkTask(param.detail, { idLink: idData });
         if (res.success) {
            setDataRealtime([{
               category: "tugas-detail-link",
               id: param.detail,
            }])
            toast.success(res.message)
            getOneData(false)
            setIdData("")
            setOpenDrawer(false)
         } else {
            toast.error(res.message);
         }
      } catch (error) {
         console.error(error);
         toast.error("Gagal menghapus file, coba lagi nanti");
      } finally {
         setLoadingModal(false)
         setOpenModal(false)
      }
   }

   useShallowEffect(() => {
      if (dataRealTime && dataRealTime.some((i: any) => i.category == 'tugas-detail-link' && i.id == param.detail)) {
         getOneData(false)
      } else if (dataRealTime && dataRealTime.some((i: any) => i.category == 'tugas-detail-status' && i.id == param.detail)) {
         getOneDataCancel()
      }
   }, [dataRealTime])

   return (
      <>
         {
            isData.length > 0
            &&
            <Box pt={20}>
               <Text fw={'bold'} c={tema.get().utama}>Link</Text>
               <Box bg={"white"} style={{
                  borderRadius: 10,
                  border: `1px solid ${"#D6D8F6"}`,
                  padding: 20
               }}>
                  {
                     isData.map((item, index) => {
                        return (
                           <Box
                              key={index}
                              style={{
                                 borderRadius: 10,
                                 border: `1px solid ${"#D6D8F6"}`,
                                 padding: 10
                              }}
                              mb={10}

                              onClick={() => {
                                 setLinkData(item.link)
                                 setIdData(item.id)
                                 setOpenDrawer(true)
                              }}
                           >
                              <Grid justify='center' align='center'>
                                 <Grid.Col span={{
                                    base: 1.5,
                                    xs: 1,
                                    sm: 1,
                                    md: 1,
                                    lg: 1,
                                    xl: 1,
                                 }}>
                                    <LuLink size={30} />
                                 </Grid.Col>
                                 <Grid.Col
                                    span={{
                                       base: 10.5,
                                       xs: 11,
                                       sm: 11,
                                       md: 11,
                                       lg: 11,
                                       xl: 11,
                                    }}
                                 >
                                    <Text style={{
                                       overflowWrap: "break-word"
                                    }} pl={isMobile ? 10 : 0} truncate="end">{item.link}</Text>
                                 </Grid.Col>
                              </Grid>
                              <Group>
                              </Group>
                           </Box>
                        )
                     })
                  }
               </Box>


               <LayoutDrawer opened={openDrawer} title={<Text truncate="end">Menu</Text>} onClose={() => setOpenDrawer(false)}>
                  <Box>
                     <Stack pt={10}>
                        <SimpleGrid cols={{ base: 3, sm: 3, lg: 3 }}>
                           {
                              <Flex onClick={() => { window.open(urlCompleted(linkData), '_blank', 'noopener,noreferrer') }} justify={'center'} align={'center'} direction={'column'} >
                                 <Box>
                                    <RiExternalLinkLine size={30} color={tema.get().utama} />
                                 </Box>
                                 <Box>
                                    <Text c={tema.get().utama}>Buka Link</Text>
                                 </Box>
                              </Flex>
                           }

                           {
                              (roleLogin.get() == "user" || roleLogin.get() == "coadmin") && !memberDivision.get() ? <></>
                                 :
                                 <Flex onClick={() => {
                                    reason == null ?
                                       setOpenModal(true)
                                       : setOpenModal(false)
                                 }} justify={'center'} align={'center'} direction={'column'} >
                                    <Box>
                                       <FaTrash size={30} color={reason == null ? tema.get().utama : "gray"} />
                                    </Box>
                                    <Box>
                                       <Text c={reason == null ? tema.get().utama : "gray"}>Hapus</Text>
                                    </Box>
                                 </Flex>
                           }
                        </SimpleGrid>
                     </Stack>
                  </Box>
               </LayoutDrawer>


               <LayoutModal loading={loadingModal} opened={isOpenModal} onClose={() => setOpenModal(false)}
                  description="Apakah Anda yakin ingin menghapus link ini? Link yang dihapus tidak dapat dikembalikan"
                  onYes={(val) => {
                     if (val) {
                        onDelete()
                     } else {
                        setOpenModal(false)
                     }
                  }} />

            </Box>
         }
      </>
   );
}

