import Styles from "@/constants/Styles"
import { setUpdateAnnouncement } from "@/lib/announcementUpdate"
import { apiDeleteAnnouncement } from "@/lib/api"
import { useAuthSession } from "@/providers/AuthProvider"
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons"
import { router } from "expo-router"
import { 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
}
export default function HeaderRightAnnouncementDetail({ id }: Props) {
   const { token, decryptToken } = useAuthSession()
   const [isVisible, setVisible] = useState(false)
   const update = useSelector((state: any) => state.announcementUpdate)
   const dispatch = useDispatch()


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

   return (
      <>
         <ButtonMenuHeader onPress={() => { setVisible(true) }} />
         <DrawerBottom animation="slide" isVisible={isVisible} setVisible={setVisible} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="pencil-outline" color="black" size={25} />}
                  title="Edit"
                  onPress={() => {
                     setVisible(false)
                     router.push(`/announcement/edit/${id}`)
                  }}
               />
               <MenuItemRow
                  icon={<Ionicons name="trash" color="black" size={25} />}
                  title="Hapus"
                  onPress={() => {
                     setVisible(false)
                     AlertKonfirmasi({
                        title: 'Konfirmasi',
                        desc: 'Apakah anda yakin ingin menghapus pengumuman ini?',
                        onPress: () => {
                           handleDelete()
                        }
                     })
                  }}
               />
            </View>
         </DrawerBottom>
      </>
   )
}