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 { InputForm } from "@/components/inputForm";
import LoadingOverlay from "@/components/loadingOverlay";
import MenuItemRow from "@/components/menuItemRow";
import Text from "@/components/Text";
import Styles from "@/constants/Styles";
import { apiEditDiscussion, apiGetDiscussionOne } from "@/lib/api";
import { setUpdateDiscussion } from "@/lib/discussionUpdate";
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 { useEffect, useState } from "react";
import { SafeAreaView, ScrollView, View } from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";

export default function DiscussionDivisionEdit() {
   const { id, detail } = useLocalSearchParams<{ id: string; detail: string }>();
   const { token, decryptToken } = useAuthSession();
   const [data, setData] = useState("");
   const update = useSelector((state: any) => state.discussionUpdate);
   const dispatch = useDispatch();
   const [loading, setLoading] = useState(false)
   const [fileForm, setFileForm] = useState<any[]>([])
   const [isModalFile, setModalFile] = useState(false)
   const [indexDelFile, setIndexDelFile] = useState<{ id: string | number; cat: "newFile" | "oldFile" }>({ id: "", cat: "newFile" })
   const [dataFile, setDataFile] = useState<{ id: string; idStorage: string; name: string; extension: string; delete?: boolean }[]>([])


   async function handleLoad() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDiscussionOne({
            id: detail,
            user: hasil,
            cat: "data",
         });
         const response2 = await apiGetDiscussionOne({
            id: detail,
            user: hasil,
            cat: "file",
         });
         setDataFile(response2.data);
         setData(response.data.desc);
      } catch (error) {
         console.error(error);
      }
   }

   useEffect(() => {
      handleLoad();
   }, []);

   async function handleUpdate() {
      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, desc: data, oldFile: dataFile
            }
         ))
         const response = await apiEditDiscussion(fd, detail);

         // const response = await apiEditDiscussion({
         //    data: { user: hasil, desc: data },
         //    id: detail,
         // });
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil mengubah data', })
            dispatch(setUpdateDiscussion({ ...update, data: !update.data }));
            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)
      }
   }

   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) {
               setFileForm((prev) => [...prev, result.assets[i]])
            }
         }
      }
   };



   function deleteFile(index: number | string, cat: "newFile" | "oldFile" | null) {
      if (cat == "newFile") {
         setFileForm([...fileForm.filter((val, i) => i !== index)])
      } else {
         setDataFile(prev =>
            prev.map(item =>
               item.id === index
                  ? { ...item, delete: true }
                  : item
            )
         );
      }
      setModalFile(false)
   }

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => {
                        router.back();
                     }}
                  />
               ),
               headerTitle: "Edit Diskusi",
               headerTitleAlign: "center",
               headerRight: () => (
                  <ButtonSaveHeader
                     disable={data == "" || loading}
                     category="update"
                     onPress={() => {
                        handleUpdate();
                     }}
                  />
               ),
            }}
         />
         <LoadingOverlay visible={loading} />
         <ScrollView showsVerticalScrollIndicator={false} style={[Styles.h100]}>
            <View style={[Styles.p15]}>
               <InputForm
                  label="Diskusi"
                  type="default"
                  placeholder="Hal yang didiskusikan"
                  required
                  value={data}
                  onChange={setData}
                  multiline
               />

               <ButtonSelect value="Upload File" onPress={pickDocumentAsync} />
               {
                  (fileForm.length > 0 || dataFile.filter((val) => !val.delete).length > 0)
                  &&
                  <View style={[Styles.borderAll, Styles.round10, Styles.p10, Styles.mb10]}>
                     <Text style={[Styles.textDefaultSemiBold]}>File</Text>
                     {
                        dataFile.filter((val) => !val.delete).map((item, index) => (
                           <BorderBottomItem
                              key={index}
                              borderType={(fileForm.length + dataFile.length) > 1 ? "bottom" : "none"}
                              icon={<MaterialCommunityIcons name="file-outline" size={25} color="black" />}
                              title={item.name + '.' + item.extension}
                              titleWeight="normal"
                              onPress={() => { setIndexDelFile({ id: item.id, cat: "oldFile" }); setModalFile(true) }}
                           />
                        ))
                     }
                     {
                        fileForm.map((item, index) => (
                           <BorderBottomItem
                              key={index}
                              borderType={fileForm.length > 1 ? "bottom" : "none"}
                              icon={<MaterialCommunityIcons name="file-outline" size={25} color="black" />}
                              title={item.name}
                              titleWeight="normal"
                              onPress={() => { setIndexDelFile({ id: index, cat: "newFile" }); setModalFile(true) }}
                           />
                        ))
                     }
                  </View>
               }
            </View>
         </ScrollView>


         <DrawerBottom animation="slide" isVisible={isModalFile} setVisible={setModalFile} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<Ionicons name="trash" color="black" size={25} />}
                  title="Hapus"
                  onPress={() => { deleteFile(indexDelFile.id, indexDelFile.cat) }}
               />
            </View>
         </DrawerBottom>

      </SafeAreaView>
   );
}
