import Styles from "@/constants/Styles"
import { setUpdateAnnouncement } from "@/lib/announcementUpdate"
import { apiDeleteAnnouncement } from "@/lib/api"
import { useAuthSession } from "@/providers/AuthProvider"
import { useTheme } from "@/providers/ThemeProvider"
import { Ionicons, 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 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 { colors } = useTheme();
   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)
            Toast.show({ type: 'small', text1: 'Berhasil menghapus data', })
            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={colors.text} size={25} />}
                  title="Edit"
                  onPress={() => {
                     setVisible(false)
                     router.push(`/announcement/edit/${id}`)
                  }}
               />
               <MenuItemRow
                  icon={<Ionicons name="trash" color={colors.text} size={25} />}
                  title="Hapus"
                  onPress={() => {
                     setVisible(false)
                     AlertKonfirmasi({
                        title: 'Konfirmasi',
                        desc: 'Apakah anda yakin ingin menghapus pengumuman ini?',
                        onPress: () => {
                           handleDelete()
                        }
                     })
                  }}
               />
            </View>
         </DrawerBottom>
      </>
   )
}