import Styles from "@/constants/Styles";
import { apiCopyDocument, apiMoveDocument } from "@/lib/api";
import { setUpdateDokumen } from "@/lib/dokumenUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { ToastAndroid, View } from "react-native";
import { useDispatch, useSelector } from "react-redux";
import DrawerBottom from "../drawerBottom";
import MenuItemRow from "../menuItemRow";
import ModalInformasi from "./modalInformasi";
import ModalSalinMove from "./modalSalinMove";

type Props = {
   idStorage: string;
   id: string;
   name: string;
   extension: string;
   category: string;
   path: string;
   share: boolean;
   createdBy: string;
   createdAt: string;
   updatedAt: string;
};

export default function ModalMore({
   onClose,
   data,
   share,
}: {
   onClose: () => void;
   data: Props[];
   share: boolean;
}) {
   const { id } = useLocalSearchParams<{ id: string }>();
   const [isInformasi, setInformasi] = useState(false);
   const [isCut, setIsCut] = useState(false);
   const [isCopy, setIsCopy] = useState(false);
   const [forbidCopy, setForbidCopy] = useState(true);
   const [nFileSelected, setNFileSelected] = useState(0);
   const { token, decryptToken } = useAuthSession();
   const dispatch = useDispatch();
   const update = useSelector((state: any) => state.dokumenUpdate);

   function cekFileSelected() {
      const cek = data.some((i: any) => i.category == "FOLDER");
      setForbidCopy(cek);
      setNFileSelected(data.length);
   }

   useEffect(() => {
      cekFileSelected();
   }, [data]);

   async function handleMove(path: string) {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiMoveDocument({
            user: hasil,
            dataItem: data,
            path,
         });
         if (response.success) {
            ToastAndroid.show("Berhasil memindahkan file", ToastAndroid.SHORT);
            dispatch(setUpdateDokumen(!update));
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT);
         }
      } catch (error) {
         console.error(error);
         ToastAndroid.show("Terjadi kesalahan", ToastAndroid.SHORT);
      } finally {
         setIsCut(false);
         onClose();
      }
   }

   async function handleCopy(path: string) {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiCopyDocument({
            user: hasil,
            dataItem: data,
            path,
            idDivision: id
         });
         if (response.success) {
            ToastAndroid.show("Berhasil menyalin file", ToastAndroid.SHORT);
            dispatch(setUpdateDokumen(!update));
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT);
         }
      } catch (error) {
         console.error(error);
         ToastAndroid.show("Terjadi kesalahan", ToastAndroid.SHORT);
      } finally {
         setIsCopy(false);
         onClose();
      }
   }

   return (
      <>
         <View style={Styles.rowItemsCenter}>
            {!share && (
               <MenuItemRow
                  icon={
                     <MaterialCommunityIcons
                        name="folder-move-outline"
                        color="black"
                        size={25}
                     />
                  }
                  title="Pindah"
                  onPress={() => {
                     setIsCut(true);
                  }}
               />
            )}
            {!forbidCopy && (
               <MenuItemRow
                  icon={
                     <MaterialCommunityIcons
                        name="folder-multiple-outline"
                        color="black"
                        size={25}
                     />
                  }
                  title="Salin"
                  onPress={() => {
                     setIsCopy(true);
                  }}
               />
            )}
            {nFileSelected == 1 && (
               <MenuItemRow
                  icon={
                     <MaterialCommunityIcons
                        name="information-variant"
                        color="black"
                        size={25}
                     />
                  }
                  title="Informasi"
                  onPress={() => {
                     setInformasi(true);
                  }}
               />
            )}
         </View>

         <DrawerBottom
            animation="slide"
            isVisible={isInformasi}
            setVisible={setInformasi}
            title="Informasi Dokumen"
            height={80}
         >
            <ModalInformasi data={data[0]} />
         </DrawerBottom>

         <ModalSalinMove
            open={isCut}
            close={() => setIsCut(false)}
            category={"move"}
            onConfirm={(value: string) => handleMove(value)}
            dataChoose={data}
         />

         <ModalSalinMove
            open={isCopy}
            close={() => setIsCopy(false)}
            category={"copy"}
            onConfirm={(value: string) => handleCopy(value)}
            dataChoose={data}
         />
      </>
   );
}
