import Styles from "@/constants/Styles"
import { apiDeleteDiscussionGeneral, apiUpdateStatusDiscussionGeneral } from "@/lib/api"
import { setUpdateDiscussionGeneralDetail } from "@/lib/discussionGeneralDetail"
import { useAuthSession } from "@/providers/AuthProvider"
import { useTheme } from "@/providers/ThemeProvider"
import { MaterialCommunityIcons, MaterialIcons } 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 = {
   id: string
   active: boolean
   status: number
}

export default function HeaderRightDiscussionGeneralDetail({ id, active, status }: Props) {
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   const [isVisible, setVisible] = useState(false)
   const entityUser = useSelector((state: any) => state.user)
   const [showModal, setShowModal] = useState(false)
   const [modalConfig, setModalConfig] = useState({ title: '', message: '', onConfirm: () => { } })
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.discussionGeneralDetailUpdate)

   async function handleUpdateStatus() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiUpdateStatusDiscussionGeneral({ id: id, data: { status: status, user: hasil } })
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil mengupdate data', })
            dispatch(setUpdateDiscussionGeneralDetail(!update))
         }
         setVisible(false)
      } catch (error) {
         console.error(error)
      }
   }

   async function handleDelete() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiDeleteDiscussionGeneral({ active: !active, user: hasil }, id)
         Toast.show({ type: 'small', text1: 'Berhasil mengupdate data', })
         dispatch(setUpdateDiscussionGeneralDetail(!update))
      } 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="account-group-outline" color={colors.text} size={25} />}
                  title="Anggota"
                  onPress={() => {
                     setVisible(false)
                     router.push(`/discussion/member/${id}`)
                  }}
               />
               {
                  entityUser.role != "user" && entityUser.role != "coadmin" &&
                  <>
                     {
                        active ?
                           (
                              <>
                                 <MenuItemRow
                                    icon={<MaterialCommunityIcons name="pencil-outline" color={colors.text} size={25} />}
                                    title="Edit"
                                    onPress={() => {
                                       setVisible(false)
                                       router.push(`/discussion/edit/${id}`)
                                    }}
                                 />
                                 <MenuItemRow
                                    icon={<MaterialIcons name="close" color={colors.text} size={25} />}
                                    title={status == 1 ? 'Tutup Diskusi' : 'Buka Diskusi'}
                                    onPress={() => {
                                       setVisible(false)
                                       setTimeout(() => {
                                          setModalConfig({
                                             title: 'Konfirmasi',
                                             message: status == 1 ? 'Apakah anda yakin ingin menutup diskusi?' : 'Apakah anda yakin ingin membuka diskusi?',
                                             onConfirm: () => handleUpdateStatus()
                                          })
                                          setShowModal(true)
                                       }, 600)
                                    }}
                                 />
                              </>
                           )
                           :
                           <MenuItemRow
                              icon={<MaterialCommunityIcons name="archive-outline" color={colors.text} size={25} />}
                              title="Aktifkan Diskusi"
                              onPress={() => {
                                 setVisible(false)
                                 setTimeout(() => {
                                    setModalConfig({
                                       title: 'Konfirmasi',
                                       message: 'Apakah anda yakin ingin mengaktifkan diskusi ini?',
                                       onConfirm: () => handleDelete()
                                    })
                                    setShowModal(true)
                                 }, 600)
                              }}
                           />

                     }
                  </>
               }
            </View>
            {
               entityUser.role != "user" && entityUser.role != "coadmin" && active &&
               <View style={[Styles.rowItemsCenter, Styles.mt15]}>
                  <MenuItemRow
                     icon={<MaterialCommunityIcons name="archive-outline" color={colors.text} size={25} />}
                     title="Arsipkan"
                     onPress={() => {
                        setVisible(false)
                        setTimeout(() => {
                           setModalConfig({
                              title: 'Konfirmasi',
                              message: 'Apakah anda yakin ingin mengarsipkan diskusi?',
                              onConfirm: () => handleDelete()
                           })
                           setShowModal(true)
                        }, 600)
                     }}
                  />
               </View>
            }
         </DrawerBottom>

         <ModalConfirmation
            visible={showModal}
            title={modalConfig.title}
            message={modalConfig.message}
            onConfirm={() => {
               setShowModal(false)
               modalConfig.onConfirm()
            }}
            onCancel={() => setShowModal(false)}
            confirmText="Ya"
            cancelText="Batal"
         />
      </>
   )
}