import Styles from "@/constants/Styles";
import { apiCreateFolderDocument, apiUploadFileDocument } from "@/lib/api";
import { setUpdateDokumen } from "@/lib/dokumenUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { MaterialCommunityIcons, MaterialIcons } from "@expo/vector-icons";
import * as DocumentPicker from "expo-document-picker";
import { useLocalSearchParams } 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 ButtonMenuHeader from "../buttonMenuHeader";
import DrawerBottom from "../drawerBottom";
import { InputForm } from "../inputForm";
import MenuItemRow from "../menuItemRow";
import ModalFloat from "../modalFloat";

export default function HeaderRightDocument({ path }: { path: string }) {
   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)

   async function handleCreateFolder() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiCreateFolderDocument({ 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) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setNewFolder(false)
      }
   }

   const pickDocumentAsync = async () => {
      let result = await DocumentPicker.getDocumentAsync({
         type: ["*/*"],
         multiple: false,
      });
      if (!result.canceled) {
         if (result.assets?.[0].uri) {
            handleUploadFile(result.assets?.[0])
         }
      }
   };

   async function handleUploadFile(file: any) {
      try {
         const hasil = await decryptToken(String(token?.current))
         const fd = new FormData()
         fd.append("file", {
            uri: file.uri,
            type: "application/octet-stream",
            name: file.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) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setVisible(false)
      }
   }


   return (
      <>
         <ButtonMenuHeader
            onPress={() => {
               setVisible(true);
            }}
         />
         <DrawerBottom
            animation="slide"
            isVisible={isVisible}
            setVisible={setVisible}
            title="Menu"
         >
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={
                     <MaterialCommunityIcons
                        name="folder-open"
                        color="black"
                        size={25}
                     />
                  }
                  title="Tambah Dokumen"
                  onPress={() => {
                     setVisible(false);
                     setNewFolder(true);
                  }}
               />

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