import Styles from "@/constants/Styles"
import { apiArchiveDiscussion, apiOpenCloseDiscussion } from "@/lib/api"
import { setUpdateDiscussion } from "@/lib/discussionUpdate"
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 | string[]
   status: number | undefined,
   isActive: boolean | undefined
}

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

   const handleOpenClose = async () => {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiOpenCloseDiscussion({ status: Number(status), user: hasil }, String(id))
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil mengubah data', })
            dispatch(setUpdateDiscussion({ ...update, data: !update.data }))
            setVisible(false)
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error : any ) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengubah data"

         Toast.show({ type: 'small', text1: message })
      } finally {
         setVisible(false)
      }
   }

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

         Toast.show({ type: 'small', text1: message })
      } finally {
         setVisible(false)
      }
   }

   return (
      <>
         <ButtonMenuHeader onPress={() => { setVisible(true) }} />
         <DrawerBottom animation="slide" isVisible={isVisible} setVisible={setVisible} title="Menu">
            <View style={Styles.rowItemsCenter}>
               {
                  isActive &&
                  <>
                     <MenuItemRow
                        icon={<MaterialCommunityIcons name="pencil-outline" color={colors.text} size={25} />}
                        title="Edit"
                        onPress={() => {
                           setVisible(false)
                           router.push(`./${id}/edit`)
                        }}
                     />
                     <MenuItemRow
                        icon={<MaterialIcons name={status == 1 ? 'close' : 'check'} color={colors.text} size={25} />}
                        title={status == 1 ? 'Tutup Diskusi' : 'Buka Diskusi'}
                        onPress={() => {
                           setVisible(false)
                           setTimeout(() => {
                              setModalConfig({
                                 title: 'Konfirmasi',
                                 message: `Apakah anda yakin ingin ${status == 1 ? 'menutup' : 'membuka'} diskusi?`,
                                 onConfirm: () => handleOpenClose()
                              })
                              setShowModal(true)
                           }, 600)
                        }}
                     />
                  </>
               }
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="archive-outline" color={colors.text} size={25} />}
                  title={isActive ? 'Arsipkan' : 'Aktifkan Diskusi'}
                  onPress={() => {
                     setVisible(false)
                     setTimeout(() => {
                        setModalConfig({
                           title: 'Konfirmasi',
                           message: isActive ? 'Apakah anda yakin ingin mengarsipkan diskusi?' : 'Apakah anda yakin ingin mengaktifkan diskusi?',
                           onConfirm: () => handleArchive()
                        })
                        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"
         />
      </>
   )
}