import Styles from "@/constants/Styles";
import { apiDeleteLinkTask, apiGetTaskOne } from "@/lib/api";
import { setUpdateTask } from "@/lib/taskUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { Ionicons } from "@expo/vector-icons";
import { useLocalSearchParams } from "expo-router";
import { useEffect, 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 DrawerBottom from "../drawerBottom";
import MenuItemRow from "../menuItemRow";
import Text from "../Text";
import ItemSectionLink from "../project/itemSectionLink";

type Props = {
   id: string
   link: string
}

export default function SectionLinkTask({ refreshing, isMemberDivision }: { refreshing: boolean, isMemberDivision: boolean }) {
   const { colors } = useTheme()
   const [isModal, setModal] = useState(false)
   const { token, decryptToken } = useAuthSession()
   const { detail } = useLocalSearchParams<{ detail: string }>()
   const [data, setData] = useState<Props[]>([])
   const update = useSelector((state: any) => state.taskUpdate)
   const dispatch = useDispatch()
   const [selectLink, setSelectLink] = useState<Props | null>(null)
   const [showDeleteModal, setShowDeleteModal] = useState(false)
   const entityUser = useSelector((state: any) => state.user);

   async function handleLoad() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetTaskOne({ id: detail, user: hasil, cat: 'link' })
         setData(response.data)
      } catch (error) {
         console.error(error)
      }
   }

   useEffect(() => {
      handleLoad()
   }, [update.link])

   useEffect(() => {
      if (refreshing)
         handleLoad();
   }, [refreshing]);

   async function handleDelete() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiDeleteLinkTask({ user: hasil, idLink: String(selectLink?.id) }, String(detail));
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil menghapus link', })
            dispatch(setUpdateTask({ ...update, link: !update.link }))
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal menghapus link"
         Toast.show({ type: 'small', text1: message })
      } finally {
         setModal(false)
      }
   }

   if (data.length === 0) return null;

   const canDelete = (entityUser.role !== "user" && entityUser.role !== "coadmin") || isMemberDivision;

   return (
      <>
         <View style={[Styles.mb15]}>
            <Text style={[Styles.textDefaultSemiBold, Styles.mv05]}>Link</Text>
            <View>
               {data.map((item, index) => (
                  <ItemSectionLink
                     key={index}
                     link={item.link}
                     canDelete={canDelete}
                     onLongPress={() => { setSelectLink(item); setModal(true) }}
                  />
               ))}
            </View>
         </View>

         <DrawerBottom animation="slide" isVisible={isModal} setVisible={setModal} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<Ionicons name="trash-outline" color={colors.text} size={25} />}
                  title="Hapus Link"
                  onPress={() => {
                     setModal(false)
                     setTimeout(() => setShowDeleteModal(true), 600)
                  }}
               />
            </View>
         </DrawerBottom>

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