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, ToastAndroid, View } from "react-native"
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 pickDocumentAsync = async () => {
      let result = await DocumentPicker.getDocumentAsync({
         type: ["*/*"],
         multiple: false
      });
      if (!result.canceled) {
         if (result.assets?.[0].uri) {
            const check = await handleCheckFile(result.assets?.[0])
            if (check) {
               setFileForm([...fileForm, result.assets?.[0]])
               setListFile([...listFile, result.assets?.[0].name])
            } else {
               ToastAndroid.show('File sudah ada', ToastAndroid.SHORT)
            }
         }
      }
   };

   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 {
         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) {
            ToastAndroid.show('Berhasil menambahkan file', ToastAndroid.SHORT)
            dispatch(setUpdateProject({ ...update, file: !update.file }))
            router.back()
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT)
         }
      } catch (error) {
         console.error(error);
         ToastAndroid.show('Terjadi kesalahan', ToastAndroid.SHORT)
      }
   }




   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Tambah File',
               headerTitleAlign: 'center',
               headerRight: () => <ButtonSaveHeader
                  disable={fileForm.length == 0 ? 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" />
               }
            </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>
   )
}