import Styles from "@/constants/Styles"
import { apiAddLinkTask, apiDeleteTask } from "@/lib/api"
import { setUpdateTask } from "@/lib/taskUpdate"
import { useAuthSession } from "@/providers/AuthProvider"
import { useTheme } from "@/providers/ThemeProvider"
import { AntDesign, Feather, Ionicons, 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 { InputForm } from "../inputForm"
import MenuItemRow from "../menuItemRow"
import ModalFloat from "../modalFloat"

type Props = {
   id: string | string[]
   division: string
   status: number | undefined,
   isAdminDivision: boolean
}

export default function HeaderRightTaskDetail({ id, division, status, isAdminDivision }: Props) {
   const { colors } = useTheme()
   const { token, decryptToken } = useAuthSession()
   const [isVisible, setVisible] = useState(false)
   const entityUser = useSelector((state: any) => state.user);
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.taskUpdate)
   const [isAddLink, setAddLink] = useState(false)
   const [showDeleteModal, setShowDeleteModal] = useState(false)
   const [link, setLink] = useState("")

   async function handleDelete() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiDeleteTask({ user: hasil }, String(id))
         if (response.success) {
            dispatch(setUpdateTask({ ...update, data: !update.data }))
            Toast.show({ type: 'small', text1: 'Berhasil menghapus tugas', })
            router.back()
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error)
      } finally {
         setVisible(false)
      }
   }

   async function handleAddLink() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiAddLinkTask({ user: hasil, link, idDivision: division }, String(id))
         if (response.success) {
            dispatch(setUpdateTask({ ...update, link: !update.link }))
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan link', })
         } else {
            Toast.show({ type: 'small', text1: 'Gagal menambahkan link', })
         }
      } catch (error) {
         console.error(error)
      } finally {
         setAddLink(false)
      }
   }

   return (
      <>
         <ButtonMenuHeader onPress={() => { setVisible(true) }} />
         <DrawerBottom animation="slide" isVisible={isVisible} setVisible={setVisible} title="Menu" height={35}>
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<AntDesign name="pluscircleo" color={colors.text} size={25} />}
                  title="Tambah Tugas"
                  onPress={() => {
                     if (status == 3) return
                     setVisible(false)
                     router.push(`./${id}/add-task`)
                  }}
                  disabled={status == 3}
               />
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="file-plus" color={colors.text} size={25} />}
                  title="Tambah File"
                  onPress={() => {
                     if (status == 3) return
                     setVisible(false)
                     router.push(`./${id}/add-file`)
                  }}
                  disabled={status == 3}
               />

               <MenuItemRow
                  icon={<Feather name="link" color={colors.text} size={25} />}
                  title="Tambah Link"
                  onPress={() => {
                     if (status == 3) return
                     setVisible(false)
                     setTimeout(() => {
                        setAddLink(true)
                     }, 600)
                  }}
                  disabled={status == 3}
               />
            </View>
            <View style={[Styles.rowItemsCenter, Styles.mt15]}>
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="file-document" color={colors.text} size={25} />}
                  title="Laporan"
                  onPress={() => {
                     if (status == 3) return
                     setVisible(false)
                     router.push(`./${id}/report`)
                  }}
                  disabled={status == 3}
               />

               {
                  ((entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision)
                  &&
                  <>
                     <MenuItemRow
                        icon={<MaterialCommunityIcons name="account-group-outline" color={colors.text} size={25} />}
                        title="Tambah Anggota"
                        onPress={() => {
                           if (status == 3) return
                           setVisible(false)
                           router.push(`./${id}/add-member`)
                        }}
                        disabled={status == 3}
                     />
                     <MenuItemRow
                        icon={<MaterialCommunityIcons name="pencil-outline" color={colors.text} size={25} />}
                        title="Edit"
                        onPress={() => {
                           if (status == 3) return
                           setVisible(false)
                           router.push(`./${id}/edit`)
                        }}
                        disabled={status == 3}
                     />
                  </>
               }
            </View>
            {
               ((entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision)
               &&
               <View style={[Styles.rowItemsCenter, Styles.mt15]}>
                  {
                     status == 3
                        ?
                        <MenuItemRow
                           icon={<Ionicons name="trash-outline" color={colors.text} size={25} />}
                           title="Hapus"
                           onPress={() => {
                              setVisible(false)
                              setTimeout(() => {
                                 setShowDeleteModal(true)
                              }, 600)
                           }}
                        />

                        :
                        <MenuItemRow
                           icon={<MaterialIcons name="close" color={colors.text} size={25} />}
                           title="Batal"
                           onPress={() => {
                              setVisible(false)
                              router.push(`./${id}/cancel`)
                           }}
                        />
                  }
               </View>
            }
         </DrawerBottom >

         <ModalConfirmation
            visible={showDeleteModal}
            title="Konfirmasi"
            message="Apakah Anda yakin ingin menghapus tugas ini? Tugas yang dihapus tidak dapat dikembalikan"
            onConfirm={() => {
               setShowDeleteModal(false)
               handleDelete()
            }}
            onCancel={() => setShowDeleteModal(false)}
            confirmText="Hapus"
            cancelText="Batal"
         />

         <ModalFloat
            title="Tambah Link"
            isVisible={isAddLink}
            setVisible={() => { setAddLink(false) }}
            onSubmit={() => { handleAddLink() }}
            disableSubmit={link == ""}
         >
            <View>
               <InputForm
                  type="default"
                  placeholder="Masukkan link"
                  value={link}
                  onChange={(text) => { setLink(text) }}
                  bg={colors.card}
               />
            </View>
         </ModalFloat>
      </>
   )
}