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 { InputForm } from "@/components/inputForm";
import LoadingCenter from "@/components/loadingCenter";
import MenuItemRow from "@/components/menuItemRow";
import ModalSelectMultiple from "@/components/modalSelectMultiple";
import Text from '@/components/Text';
import Styles from "@/constants/Styles";
import { setUpdateAnnouncement } from "@/lib/announcementUpdate";
import { apiEditAnnouncement, apiGetAnnouncementOne } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { Entypo, 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";


type GroupDivision = {
   id: string;
   name: string;
   Division: {
      id: string;
      name: string;
   }[];
}

export default function EditAnnouncement() {
   const { id } = useLocalSearchParams<{ id: string }>();
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.announcementUpdate)
   const { token, decryptToken } = useAuthSession();
   const { colors } = useTheme();
   const [modalDivisi, setModalDivisi] = useState(false);
   const [disableBtn, setDisableBtn] = useState(true);
   const [dataMember, setDataMember] = useState<any>([]);
   const [fileForm, setFileForm] = useState<any[]>([])
   const [dataFile, setDataFile] = useState<{ id: string; idStorage: string; name: string; extension: string; delete?: boolean }[]>([])
   const [indexDelFile, setIndexDelFile] = useState<{ id: string | number; cat: "newFile" | "oldFile" }>({ id: "", cat: "newFile" })
   const [isModalFile, setModalFile] = useState(false)
   const [loading, setLoading] = useState(false)
   const [dataForm, setDataForm] = useState({
      title: "",
      desc: "",
   });
   const [error, setError] = useState({
      title: false,
      desc: false,
   });

   async function handleLoad() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetAnnouncementOne({ id: id, user: hasil });
         setDataForm(response.data);

         const arrNew: GroupDivision[] = []
         const coba = Object.keys(response.member).map((v: any, i: any) => {
            const newObject = {
               "id": response.member[v][0].idGroup,
               "name": v,
               "Division": response.member[v]
            }

            response.member[v].map((v: any, i: any) => {
               newObject["Division"][i] = {
                  "id": v.idDivision,
                  "name": v.division
               }
            })
            arrNew.push(newObject)
         })
         setDataMember(arrNew);
         setDataFile(response.file);
      } catch (error) {
         console.error(error);
      }
   }

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

   function validationForm(cat: string, val: any) {
      if (cat == "title") {
         setDataForm({ ...dataForm, title: val });
         if (val == "" || val == "null") {
            setError({ ...error, title: true });
         } else {
            setError({ ...error, title: false });
         }
      } else if (cat == "desc") {
         setDataForm({ ...dataForm, desc: val });
         if (val == "" || val == "null") {
            setError({ ...error, desc: true });
         } else {
            setError({ ...error, desc: false });
         }
      }
   }

   function checkForm() {
      if (
         Object.values(error).some((v) => v == true) ||
         Object.values(dataForm).some((v) => v == "")
      ) {
         setDisableBtn(true);
      } else {
         setDisableBtn(false);
      }
   }

   useEffect(() => {
      checkForm();
   }, [error, dataForm]);

   async function handleEdit() {
      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(
            {
               ...dataForm, user: hasil, groups: dataMember, oldFile: dataFile
            }
         ))

         const response = await apiEditAnnouncement(fd, id);
         if (response.success) {
            dispatch(setUpdateAnnouncement(!update))
            Toast.show({ type: 'small', text1: 'Berhasil mengubah data', })
            router.back();
         }
      } catch (error) {
         console.error(error);
      } 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 style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Edit Pengumuman",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonSaveHeader
               //       disable={disableBtn || loading ? true : false}
               //       category="update"
               //       onPress={() => {
               //          dataMember.length == 0
               //             ? Toast.show({ type: 'small', text1: "Anda belum memilih divisi", })
               //             : handleEdit();
               //       }}
               //    />
               // ),
               header: () => (
                  <AppHeader
                     title="Edit Pengumuman"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={disableBtn || loading ? true : false}
                           category="update"
                           onPress={() => {
                              dataMember.length == 0
                                 ? Toast.show({ type: 'small', text1: "Anda belum memilih divisi", })
                                 : handleEdit();
                           }}
                        />
                     }
                  />
               )
            }}
         />
         {loading && <LoadingCenter />}
         <ScrollView
            showsVerticalScrollIndicator={false}
            style={[Styles.h100, { backgroundColor: colors.background }]}
         >
            <View style={[Styles.p15]}>
               <InputForm
                  label="Judul"
                  type="default"
                  placeholder="Judul Pengumuman"
                  required
                  error={error.title}
                  bg={colors.card}
                  errorText="Judul harus diisi"
                  onChange={(val) => validationForm("title", val)}
                  value={dataForm.title}
               />
               <InputForm
                  label="Pengumuman"
                  type="default"
                  placeholder="Deskripsi Pengumuman"
                  required
                  error={error.desc}
                  bg={colors.card}
                  errorText="Pengumuman harus diisi"
                  onChange={(val) => validationForm("desc", val)}
                  value={dataForm.desc}
                  multiline
               />
               <ButtonSelect value="Upload File" onPress={pickDocumentAsync} />
               {
                  (fileForm.length > 0 || dataFile.filter((val) => !val.delete).length > 0)
                  &&
                  <>
                     <View style={[Styles.rowSpaceBetween, Styles.mv05]}>
                        <Text style={[Styles.textDefaultSemiBold]}>File</Text>
                        <Text style={[Styles.textDefault]}>{fileForm.length + dataFile.filter((val) => !val.delete).length} file</Text>
                     </View>
                     <View style={[Styles.borderAll, Styles.round05, Styles.p10, Styles.mb10, { borderColor: colors.icon + '20' }]}>
                        {
                           dataFile.filter((val) => !val.delete).map((item, index) => (
                              <BorderBottomItem
                                 key={index}
                                 borderType={dataFile.filter((val) => !val.delete).length - 1 == index && fileForm.length == 0 ? "none" : "bottom"}
                                 icon={<MaterialCommunityIcons name="file-outline" size={25} color={colors.text} />}
                                 title={item.name + '.' + item.extension}
                                 titleWeight="normal"
                                 bgColor="transparent"
                                 onPress={() => { setIndexDelFile({ id: item.id, cat: "oldFile" }); setModalFile(true) }}
                              />
                           ))
                        }
                        {
                           fileForm.map((item, index) => (
                              <BorderBottomItem
                                 key={index}
                                 borderType={fileForm.length - 1 == index ? "none" : "bottom"}
                                 icon={<MaterialCommunityIcons name="file-outline" size={25} color={colors.text} />}
                                 title={item.name}
                                 titleWeight="normal"
                                 bgColor="transparent"
                                 onPress={() => { setIndexDelFile({ id: index, cat: "newFile" }); setModalFile(true) }}
                              />
                           ))
                        }
                     </View>
                  </>
               }
               <ButtonSelect
                  value="Pilih divisi penerima pengumuman"
                  onPress={() => {
                     setModalDivisi(true)
                  }}
               />
               {
                  dataMember.length > 0
                  &&
                  <>
                     <View style={[Styles.rowSpaceBetween, Styles.mv05]}>
                        <Text style={[Styles.textDefaultSemiBold]}>Divisi</Text>
                     </View>
                     <View style={[Styles.borderAll, Styles.round05, Styles.p10, { borderColor: colors.icon + '20' }]}>
                        {
                           dataMember.map((item: { name: any; Division: any }, index: any) => {
                              return (
                                 <View key={index}>
                                    <Text style={[Styles.textDefaultSemiBold]}>{item.name}</Text>
                                    {
                                       item.Division.map((division: any, i: any) => (
                                          <View key={i} style={[Styles.rowItemsCenter, Styles.w90]}>
                                             <Entypo name="dot-single" size={24} color={colors.text} />
                                             <Text style={[Styles.textDefault]} numberOfLines={1} ellipsizeMode='tail'>{division.name}</Text>
                                          </View>
                                       ))
                                    }
                                 </View>
                              )
                           })
                        }
                     </View>
                  </>
               }
            </View>
         </ScrollView>

         <ModalSelectMultiple
            choose="dinas"
            title="Pilih Divisi"
            category="choose-division"
            open={modalDivisi}
            close={setModalDivisi}
            onSelect={(val) => {
               setDataMember(val)
               setModalDivisi(false)
            }}
            value={dataMember}
         />

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