import Styles from "@/constants/Styles"
import { apiDeleteTask, apiGetDivisionOneFeature } from "@/lib/api"
import { setUpdateTask } from "@/lib/taskUpdate"
import { useAuthSession } from "@/providers/AuthProvider"
import { AntDesign, Ionicons, MaterialCommunityIcons, MaterialIcons } from "@expo/vector-icons"
import { router } from "expo-router"
import { useEffect, useState } from "react"
import { ToastAndroid, View } from "react-native"
import { useDispatch, useSelector } from "react-redux"
import AlertKonfirmasi from "../alertKonfirmasi"
import ButtonMenuHeader from "../buttonMenuHeader"
import DrawerBottom from "../drawerBottom"
import MenuItemRow from "../menuItemRow"

type Props = {
   id: string | string[]
   division: string
   status: number | undefined
}

export default function HeaderRightTaskDetail({ id, division, status }: Props) {
   const { token, decryptToken } = useAuthSession()
   const [isVisible, setVisible] = useState(false)
   const entityUser = useSelector((state: any) => state.user);
   const [isMemberDivision, setIsMemberDivision] = useState(false);
   const [isAdminDivision, setIsAdminDivision] = useState(false);
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.taskUpdate)

   async function handleCheckMember() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDivisionOneFeature({
            id: division,
            user: hasil,
            cat: "check-member",
         });

         setIsMemberDivision(response.data);

         const response2 = await apiGetDivisionOneFeature({
            id: division,
            user: hasil,
            cat: "check-admin",
         });
         setIsAdminDivision(response2.data);
      } catch (error) {
         console.error(error);
      }
   }

   useEffect(() => {
      handleCheckMember()
   }, [])

   async function handleDelete() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiDeleteTask({ user: hasil }, String(id))
         if (response.success) {
            dispatch(setUpdateTask({ ...update, data: !update.data }))
            ToastAndroid.show('Berhasil menghapus tugas', ToastAndroid.SHORT)
            router.back()
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT)
         }
      } catch (error) {
         console.error(error)
      } finally {
         setVisible(false)
      }
   }

   return (
      <>
         {
            (entityUser.role == "user" || entityUser.role == "coadmin") && !isMemberDivision
               ? <></>
               :
               <ButtonMenuHeader onPress={() => { setVisible(true) }} />
         }
         <DrawerBottom animation="slide" isVisible={isVisible} setVisible={setVisible} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<AntDesign name="pluscircle" color="black" size={25} />}
                  title="Tambah Tugas"
                  onPress={() => {
                     if (status == 3) return
                     setVisible(false)
                     router.push(`./${id}/add-task`)
                  }}
                  disabled={status == 3}
               />
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="file-plus" color="black" size={25} />}
                  title="Tambah File"
                  onPress={() => {
                     if (status == 3) return
                     setVisible(false)
                     router.push(`./${id}/add-file`)
                  }}
                  disabled={status == 3}
               />
               {
                 ( (entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision)
                  &&
                  <MenuItemRow
                     icon={<MaterialIcons name="groups" color="black" size={25} />}
                     title="Tambah Anggota"
                     onPress={() => {
                        if (status == 3) return
                        setVisible(false)
                        router.push(`./${id}/add-member`)
                     }}
                     disabled={status == 3}
                  />

               }

            </View>

            {
               ( (entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision )
               &&
               <View style={[Styles.rowItemsCenter, Styles.mt15]}>
                  <MenuItemRow
                     icon={<MaterialCommunityIcons name="pencil-outline" color="black" size={25} />}
                     title="Edit"
                     onPress={() => {
                        if (status == 3) return
                        setVisible(false)
                        router.push(`./${id}/edit`)
                     }}
                     disabled={status == 3}
                  />
                  {
                     status == 3
                        ?
                        <MenuItemRow
                           icon={<Ionicons name="trash" color="black" size={25} />}
                           title="Hapus"
                           onPress={() => {
                              AlertKonfirmasi({
                                 title: 'Konfirmasi',
                                 desc: 'Apakah Anda yakin ingin menghapus tugas ini? Tugas yang dihapus tidak dapat dikembalikan',
                                 onPress: () => { handleDelete() }
                              })
                           }}
                        />

                        :
                        <MenuItemRow
                           icon={<MaterialIcons name="close" color="black" size={25} />}
                           title="Batal"
                           onPress={() => {
                              setVisible(false)
                              router.push(`./${id}/cancel`)
                           }}
                        />
                  }
               </View>
            }
         </DrawerBottom>
      </>
   )
}