import Styles from "@/constants/Styles"
import { apiDeleteUser, apiToggleApprover } from "@/lib/api"
import { setUpdateMember } from "@/lib/memberSlice"
import { useAuthSession } from "@/providers/AuthProvider"
import { useTheme } from "@/providers/ThemeProvider"
import { MaterialCommunityIcons } from "@expo/vector-icons"
import { router } from "expo-router"
import { useState } from "react"
import { View } from "react-native"
import Toast from "react-native-toast-message"
import { useDispatch, useSelector } from "react-redux"
import ModalConfirmation from "../ModalConfirmation"
import ButtonMenuHeader from "../buttonMenuHeader"
import DrawerBottom from "../drawerBottom"
import MenuItemRow from "../menuItemRow"

type Props = {
   active: any,
   id: string,
   isApprover: boolean,
}

export default function HeaderRightMemberDetail({ active, id, isApprover }: Props) {
   const { token, decryptToken } = useAuthSession()
   const [isVisible, setVisible] = useState(false)
   const update = useSelector((state: any) => state.memberUpdate)
   const entityUser = useSelector((state: any) => state.user)
   const [showModalActive, setShowModalActive] = useState(false)
   const [showModalApprover, setShowModalApprover] = useState(false)
   const { colors } = useTheme();
   const dispatch = useDispatch()

   async function handleActive() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiDeleteUser({ user: hasil, isActive: active }, id)
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil mengupdate data', })
            dispatch(setUpdateMember(!update))
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengupdate data"
         Toast.show({ type: 'small', text1: message })
      } finally {
         setVisible(false)
      }
   }

   async function handleToggleApprover() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiToggleApprover({ user: hasil, isApprover: !isApprover }, id)
         if (response.success) {
            Toast.show({ type: 'small', text1: response.message })
            dispatch(setUpdateMember(!update))
         } else {
            Toast.show({ type: 'small', text1: response.message })
         }
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengupdate data"
         Toast.show({ type: 'small', text1: message })
      } finally {
         setShowModalApprover(false)
      }
   }

   const canManageApprover = ['supadmin', 'developer'].includes(entityUser.role)

   return (
      <>
         <ButtonMenuHeader onPress={() => { setVisible(true) }} />
         <DrawerBottom animation="slide" isVisible={isVisible} setVisible={setVisible} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="toggle-switch-off-outline" color={colors.text} size={25} />}
                  title={active ? "Nonaktifkan" : "Aktifkan"}
                  onPress={() => {
                     setVisible(false)
                     setTimeout(() => setShowModalActive(true), 600)
                  }}
               />
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="pencil-outline" color={colors.text} size={25} />}
                  title="Edit"
                  onPress={() => {
                     setVisible(false)
                     router.push(`/member/edit/${id}`)
                  }}
               />
               {canManageApprover && (
                  <MenuItemRow
                     icon={<MaterialCommunityIcons name="shield-check-outline" color={colors.text} size={25} />}
                     title={isApprover ? "Revoke Approver" : "Jadikan Approver"}
                     color={colors.text}
                     onPress={() => {
                        setVisible(false)
                        setTimeout(() => setShowModalApprover(true), 600)
                     }}
                  />
               )}
            </View>
         </DrawerBottom>

         <ModalConfirmation
            visible={showModalActive}
            title="Konfirmasi"
            message={active ? 'Apakah anda yakin ingin menonaktifkan anggota ini?' : 'Apakah anda yakin ingin mengaktifkan anggota ini?'}
            onConfirm={() => {
               setShowModalActive(false)
               handleActive()
            }}
            onCancel={() => setShowModalActive(false)}
            confirmText="Konfirmasi"
            cancelText="Batal"
         />

         <ModalConfirmation
            visible={showModalApprover}
            title="Konfirmasi"
            message={isApprover ? 'Apakah anda yakin ingin mencabut status approver user ini?' : 'Apakah anda yakin ingin menjadikan user ini sebagai approver?'}
            onConfirm={handleToggleApprover}
            onCancel={() => setShowModalApprover(false)}
            confirmText="Konfirmasi"
            cancelText="Batal"
         />
      </>
   )
}