import Styles from "@/constants/Styles";
import { apiCopyDocument, apiMoveDocument } from "@/lib/api";
import { setUpdateDokumen } from "@/lib/dokumenUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { MaterialCommunityIcons } 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 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 { colors } = useTheme();
   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) {
            Toast.show({ type: 'small', text1: 'Berhasil memindahkan file', });
            dispatch(setUpdateDokumen(!update));
         } else {
            Toast.show({ type: 'small', text1: response.message, });
         }
      } catch (error : any ) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal memindahkan file"

         Toast.show({ type: 'small', text1: message })
      } 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) {
            Toast.show({ type: 'small', text1: 'Berhasil menyalin file', });
            dispatch(setUpdateDokumen(!update));
         } else {
            Toast.show({ type: 'small', text1: response.message, });
         }
      } catch (error : any ) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal menyalin file"

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

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

         <DrawerBottom
            animation="slide"
            isVisible={isInformasi}
            setVisible={() => setInformasi(false)}
            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}
         />
      </>
   );
}
