import Styles from "@/constants/Styles";
import { apiCreateFolderDocument } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useLocalSearchParams } from "expo-router";
import { useState } from "react";
import { Pressable, View } from "react-native";
import Toast from "react-native-toast-message";
import Text from "../Text";
import { InputForm } from "../inputForm";
import ModalFloat from "../modalFloat";

export function ModalNewFolder({ path, onCreated }: { path: string, onCreated: () => void }) {
   const { token, decryptToken } = useAuthSession()
   const [newFolder, setNewFolder] = useState(false)
   const [name, setName] = useState("")
   const [loadingFolder, setLoadingFolder] = useState(false)
   const { id } = useLocalSearchParams<{ id: string }>();


   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', })
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         onCreated()
         setLoadingFolder(false)
         setNewFolder(false)
      }
   }

   return (
      <>
         <Pressable style={[Styles.pv05, Styles.borderRight, { width: '50%' }]} onPress={() => setNewFolder(true)}>
            <Text style={[Styles.textDefaultSemiBold, { textAlign: 'center' }]}>FOLDER BARU</Text>
         </Pressable>

         <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>
      </>
   )
}