import BorderBottomItem from "@/components/borderBottomItem"
import ButtonBackHeader from "@/components/buttonBackHeader"
import ButtonSaveHeader from "@/components/buttonSaveHeader"
import ButtonSelect from "@/components/buttonSelect"
import DrawerBottom from "@/components/drawerBottom"
import MenuItemRow from "@/components/menuItemRow"
import Styles from "@/constants/Styles"
import { apiAddFileProject, apiCheckFileProject } from "@/lib/api"
import { setUpdateProject } from "@/lib/projectUpdate"
import { useAuthSession } from "@/providers/AuthProvider"
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons"
import * as DocumentPicker from "expo-document-picker"
import { router, Stack, useLocalSearchParams } from "expo-router"
import { useState } from "react"
import { ActivityIndicator, SafeAreaView, ScrollView, Text, View } from "react-native"
import Toast from "react-native-toast-message"
import { useDispatch, useSelector } from "react-redux"

export default function ProjectAddFile() {
   const { id } = useLocalSearchParams<{ id: string }>()
   const [fileForm, setFileForm] = useState<any[]>([])
   const [listFile, setListFile] = useState<any[]>([])
   const [indexDelFile, setIndexDelFile] = useState<number>(0)
   const [isModal, setModal] = useState(false)
   const { token, decryptToken } = useAuthSession()
   const [loadingCheck, setLoadingCheck] = useState(false)
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.projectUpdate)
   const [loading, setLoading] = useState(false)

   const pickDocumentAsync = async () => {
      let result = await DocumentPicker.getDocumentAsync({
         type: ["*/*"],
         multiple: true
      });

      if (!result.canceled) {
         for (let i = 0; i < result.assets?.length; i++) {
            if (result.assets?.[i].uri) {
               const check = await handleCheckFile(result.assets?.[i])
               if (check) {
                  setFileForm((prev) => [...prev, result.assets?.[i]])
                  setListFile((prev) => [...prev, result.assets?.[i].name])
               } else {
                  Toast.show({ type: 'small', text1: 'File yg telah terupload tidak bisa diupload ulang', })
               }
            }
         }
      }
   };

   function deleteFile(index: number) {
      setListFile([...listFile.filter((val, i) => i !== index)])
      setFileForm([...fileForm.filter((val, i) => i !== index)])
      setModal(false)
   }

   async function handleCheckFile(val: any) {
      try {
         setLoadingCheck(true)
         const hasil = await decryptToken(String(token?.current))
         const fd = new FormData();

         fd.append("file", {
            uri: val.uri,
            type: 'application/octet-stream',
            name: val.name,
         } as any);

         fd.append(
            "data",
            JSON.stringify({
               user: hasil,
            })
         );

         const response = await apiCheckFileProject({ data: fd, id: id })
         return response.success
      } catch (error) {
         console.error(error);
         return false
      } finally {
         setLoadingCheck(false)
      }
   }


   async function handleAddFile() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         const fd = new FormData();

         for (let i = 0; i < fileForm.length; i++) {
            fd.append(`file${i}`, {
               uri: fileForm[i].uri,
               type: 'application/octet-stream',
               name: fileForm[i].name,
            } as any);
         }

         fd.append(
            "data",
            JSON.stringify({
               user: hasil,
            })
         );


         const response = await apiAddFileProject({ data: fd, id: id })
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan file', })
            dispatch(setUpdateProject({ ...update, file: !update.file }))
            router.back()
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error);
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setLoading(false)
      }
   }




   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Tambah File',
               headerTitleAlign: 'center',
               headerRight: () => <ButtonSaveHeader
                  disable={fileForm.length == 0 || loading ? true : false}
                  category="create"
                  onPress={() => { handleAddFile() }} />
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <ButtonSelect value="Upload File" onPress={pickDocumentAsync} />
               {
                  listFile.length > 0 && (
                     <View style={[Styles.mb15]}>
                        <Text style={[Styles.textDefaultSemiBold, Styles.mv05]}>File</Text>
                        <View style={[Styles.wrapPaper]}>
                           {
                              listFile.map((item, index) => (
                                 <BorderBottomItem
                                    key={index}
                                    borderType="all"
                                    icon={<MaterialCommunityIcons name="file-outline" size={25} color="black" />}
                                    title={item}
                                    titleWeight="normal"
                                    onPress={() => { setIndexDelFile(index); setModal(true) }}
                                 />
                              ))
                           }
                        </View>
                     </View>
                  )
               }
               {
                  loadingCheck && <ActivityIndicator size="small" />
               }
               {
                  loading && <ActivityIndicator size="large" />
               }
            </View>
         </ScrollView>
         <DrawerBottom animation="slide" isVisible={isModal} setVisible={setModal} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<Ionicons name="trash" color="black" size={25} />}
                  title="Hapus"
                  onPress={() => { deleteFile(indexDelFile) }}
               />
            </View>
         </DrawerBottom>
      </SafeAreaView>
   )
}