import Styles from "@/constants/Styles";
import { apiCreateFolderDocument, apiUploadFileDocument } from "@/lib/api";
import { setUpdateDokumen } from "@/lib/dokumenUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { MaterialCommunityIcons, MaterialIcons } from "@expo/vector-icons";
import * as DocumentPicker from "expo-document-picker";
import { useLocalSearchParams } from "expo-router";
import { useState } from "react";
import { ActivityIndicator, View } from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";
import ButtonMenuHeader from "../buttonMenuHeader";
import DrawerBottom from "../drawerBottom";
import { InputForm } from "../inputForm";
import MenuItemRow from "../menuItemRow";
import ModalFloat from "../modalFloat";

export default function HeaderRightDocument({ path, isMember }: { path: string, isMember: boolean }) {
   const { colors } = useTheme();
   const [isVisible, setVisible] = useState(false);
   const [newFolder, setNewFolder] = useState(false);
   const { id } = useLocalSearchParams<{ id: string }>();
   const [name, setName] = useState("");
   const { token, decryptToken } = useAuthSession()
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.dokumenUpdate)
   const [loading, setLoading] = useState(false)
   const [loadingFolder, setLoadingFolder] = useState(false)
   const entityUser = useSelector((state: any) => state.user)

   async function handleCreateFolder() {
      try {
         setLoadingFolder(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiCreateFolderDocument({ data: { user: hasil, name, path, idDivision: id } })
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil membuat folder baru', })
            dispatch(setUpdateDokumen(!update))
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error : any ) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal membuat folder"

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

   const pickDocumentAsync = async () => {
      let result = await DocumentPicker.getDocumentAsync({
         type: ["*/*"],
         multiple: true,
      });
      if (!result.canceled) {
         let file: any[] = []
         for (let i = 0; i < result.assets?.length; i++) {
            if (result.assets?.[i].uri) {
               file.push(result.assets?.[i])
            }
         }
         handleUploadFile(file)
      }
   };

   async function handleUploadFile(file: any[]) {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         const fd = new FormData()
         for (let i = 0; i < file.length; i++) {
            fd.append(`file${i}`, {
               uri: file[i].uri,
               type: "application/octet-stream",
               name: file[i].name,
            } as any);
         }
         fd.append(
            "data",
            JSON.stringify({
               idPath: path,
               idDivision: id,
               user: hasil,
            })
         )

         const response = await apiUploadFileDocument({ data: fd })
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil mengunggah 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 mengunggah file"

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


   return (
      <>
         {
            ((entityUser.role != "user" && entityUser.role != "coadmin") || isMember) &&
            <ButtonMenuHeader
               onPress={() => {
                  setVisible(true);
               }}
            />
         }
         <DrawerBottom
            animation="slide"
            isVisible={isVisible}
            setVisible={() => { setVisible(false) }}
            title="Menu"
         >
            <View style={Styles.rowItemsCenter}>
               {
                  loading ?
                     <View style={[Styles.contentItemCenter, Styles.w100, Styles.h100]}>
                        <ActivityIndicator size="large" />
                     </View>
                     :
                     <>
                        <MenuItemRow
                           icon={
                              <MaterialCommunityIcons
                                 name="folder-open"
                                 color={colors.text}
                                 size={25}
                              />
                           }
                           title="Tambah Folder"
                           onPress={() => {
                              setVisible(false);
                              setTimeout(() => {
                                 setNewFolder(true);
                              }, 600);
                           }}
                        />

                        <MenuItemRow
                           icon={<MaterialIcons name="upload-file" color={colors.text} size={25} />}
                           title="Upload File"
                           onPress={pickDocumentAsync}
                        />
                     </>
               }
            </View>
         </DrawerBottom>
         <ModalFloat
            title="Buat Folder Baru"
            isVisible={newFolder}
            setVisible={() => { setNewFolder(false) }}
            disableSubmit={name == "" || loadingFolder}
            onSubmit={() => { handleCreateFolder() }}
         >
            <View>
               <InputForm
                  type="default"
                  placeholder="Nama Folder"
                  required
                  label="Nama Folder"
                  onChange={(value: string) => { setName(value) }}
               />
            </View>
         </ModalFloat>
      </>
   );
}
