"use client"
import { globalRole, LayoutDrawer, LayoutNavbarNew, SkeletonList, TEMA } from '@/module/_global';
import LayoutModal from '@/module/_global/layout/layout_modal';
import { useHookstate } from '@hookstate/core';
import { ActionIcon, Avatar, Box, Divider, Grid, Group, Text } from '@mantine/core';
import { useMediaQuery, useShallowEffect } from '@mantine/hooks';
import { useParams, useRouter } from 'next/navigation';
import { useState } from 'react';
import toast from 'react-hot-toast';
import { AiOutlineUserAdd } from 'react-icons/ai';
import { FaUserTie } from 'react-icons/fa6';
import { IoIosCloseCircle } from 'react-icons/io';
import { funDelMemberDiscussionGeneral, funGetOneDiscussionGeneral } from '../lib/api_discussion_general';
import { IFormMemberDisscussionGeneral } from '../lib/type_discussion_general';


export default function MemberDiscussionGeneral() {
   const router = useRouter()
   const [openDrawer, setDrawer] = useState(false)
   const param = useParams<{ id: string }>()
   const [member, setMember] = useState<IFormMemberDisscussionGeneral[]>([])
   const [loading, setLoading] = useState(true)
   const [valChooseMemberId, setChooseMemberId] = useState("")
   const [valChooseMemberName, setChooseMemberName] = useState("")
   const [isOpenModal, setOpenModal] = useState(false)
   const roleLogin = useHookstate(globalRole)
   const isMobile = useMediaQuery('(max-width: 455px)')
   const isMobile2 = useMediaQuery("(max-width: 438px)")
   const tema = useHookstate(TEMA)
   const [loadingDelete, setLoadingDelete] = useState(false)

   async function getOneData(loading: boolean) {
      try {
         setLoading(loading)
         const res = await funGetOneDiscussionGeneral(param.id, "?cat=anggota");
         if (res.success) {
            setMember(res.data)
         } else {
            toast.error(res.message);
         }
      } catch (error) {
         console.error(error);
         toast.error("Gagal mendapatkan data, coba lagi nanti");
      } finally {
         setLoading(false)
      }
   }

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


   async function onClickMember(id: string, name: string) {
      setChooseMemberId(id)
      setChooseMemberName(name)
      setDrawer(true)
   }


   async function deleteMember() {
      try {
         setLoadingDelete(true)
         const res = await funDelMemberDiscussionGeneral(param.id, { idUser: valChooseMemberId })
         if (res.success) {
            toast.success(res.message)
            setDrawer(false)
            getOneData(false)
         } else {
            toast.error(res.message)
         }
      } catch (error) {
         console.error(error);
         toast.error("Gagal mendapatkan divisi, coba lagi nanti");
      } finally {
         setLoadingDelete(false)
         setOpenModal(false)
      }
   }


   return (
      <Box>
         <LayoutNavbarNew back={"/discussion/" + param.id} title="Anggota Diskusi" menu={<></>} />
         <Box p={20}>
            <Box>
               <Box>
                  <Text>{member.length} Anggota</Text>
               </Box>
               <Box p={20} bg={"white"} style={{
                  borderRadius: 10,
                  border: `1px solid ${tema.get().bgTotalKegiatan}`,
               }}>
                  <Box>
                     {!loading ?
                        roleLogin.get() != "user" && roleLogin.get() != "coadmin" ?
                           <Group align='center' onClick={() => router.push('/discussion/' + param.id + '/add-member/')}>
                              <Avatar size={'lg'}>
                                 <AiOutlineUserAdd size={30} color={tema.get().utama} />
                              </Avatar>
                              <Text fz={isMobile ? 14 : 16}>Tambah Anggota</Text>
                           </Group>
                           : <></>
                        :
                        <></>
                     }
                  </Box>
                  <Box pt={10}>
                     <Box mb={10}>
                        {loading
                           ? Array(6)
                              .fill(null)
                              .map((_, i) => (
                                 <Box key={i}>
                                    <SkeletonList />
                                 </Box>
                              ))
                           : member.map((v, i) => {
                              return (
                                 <Box key={i}>
                                    <Grid align='center' mt={10}
                                       onClick={() => { onClickMember(v.idUser, v.name) }}
                                    >
                                       <Grid.Col span={1}>
                                          <Avatar src={`https://wibu-storage.wibudev.com/api/files/${v.img}`} alt="it's me" size={'lg'} />
                                       </Grid.Col>
                                       <Grid.Col span={11}>
                                          <Text c={tema.get().utama} fw={"bold"} truncate="end" pl={isMobile2 ? 40 : 30} fz={isMobile ? 14 : 16}>
                                             {v.name}
                                          </Text>
                                       </Grid.Col>
                                    </Grid>
                                    <Box mt={10}>
                                       <Divider size={"xs"} />
                                    </Box>
                                 </Box>
                              );
                           })
                        }
                     </Box>
                  </Box>
               </Box>
            </Box>
         </Box>

         <LayoutDrawer opened={openDrawer} onClose={() => setDrawer(false)} title={valChooseMemberName}>
            <Box>
               <Group align='center' mb={20} onClick={() => { router.push('/member/' + valChooseMemberId) }} >
                  <ActionIcon variant="light" size={60} aria-label="admin" radius="xl">
                     <FaUserTie size={30} color={tema.get().utama} />
                  </ActionIcon>
                  <Text c={tema.get().utama}>Lihat Profil</Text>
               </Group>
               {
                  (roleLogin.get() != "user" && roleLogin.get() != "coadmin") &&
                  <Group align='center' onClick={() => setOpenModal(true)}>
                     <ActionIcon variant="light" size={60} aria-label="admin" radius="xl">
                        <IoIosCloseCircle size={40} color={tema.get().utama} />
                     </ActionIcon>
                     <Text c={tema.get().utama}>Keluarkan dari diskusi</Text>
                  </Group>
               }
            </Box>
         </LayoutDrawer>

         <LayoutModal loading={loadingDelete} opened={isOpenModal} onClose={() => setOpenModal(false)}
            description="Apakah Anda yakin ingin mengeluarkan anggota?"
            onYes={(val) => {
               if (!val) {
                  setOpenModal(false)
               } else {
                  deleteMember()
               }
            }} />
      </Box>
   );
}
