import AppHeader from "@/components/AppHeader";
import BorderBottomItem from "@/components/borderBottomItem";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import ButtonSelect from "@/components/buttonSelect";
import DrawerBottom from "@/components/drawerBottom";
import MenuItemRow from "@/components/menuItemRow";
import Text from "@/components/Text";
import Styles from "@/constants/Styles";
import { apiAddFileTask, apiCheckFileTask } from "@/lib/api";
import { setUpdateTask } from "@/lib/taskUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
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,
   View
} from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";

export default function TaskDivisionAddFile() {
   const { colors } = useTheme();
   const { id, detail } = useLocalSearchParams<{ id: string; detail: 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.taskUpdate);
   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 sudah ada', })
               }
            }
         }
      }
   };

   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 apiCheckFileTask({ data: fd, id: detail });
         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 apiAddFileTask({ data: fd, id: detail });
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan file', })
            dispatch(setUpdateTask({ ...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 style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Tambah File",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonSaveHeader
               //       category="create"
               //       disable={fileForm.length == 0 || loading ? true : false}
               //       onPress={() => { handleAddFile() }}
               //    />
               // ),
               header: () => (
                  <AppHeader
                     title="Tambah File"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           category="create"
                           disable={fileForm.length == 0 || loading ? true : false}
                           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, { backgroundColor: colors.card, borderColor: colors.background }]}>
                           {
                              listFile.map((item, index) => (
                                 <BorderBottomItem
                                    key={index}
                                    borderType="all"
                                    icon={<MaterialCommunityIcons name="file-outline" size={25} color={colors.text} />}
                                    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={colors.text} size={25} />}
                  title="Hapus"
                  onPress={() => { deleteFile(indexDelFile) }}
               />
            </View>
         </DrawerBottom>
      </SafeAreaView>
   );
}
