import Styles from "@/constants/Styles";
import { apiCreateFolderDocument } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
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 { colors } = useTheme()
   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 : any ) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal membuat folder"

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

   return (
      <>
         <Pressable style={[Styles.pv05, Styles.borderRight, { width: '50%', borderColor: colors.background }]} 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>
      </>
   )
}