import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import ButtonSelect from "@/components/buttonSelect";
import { InputForm } from "@/components/inputForm";
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 { Entypo } from "@expo/vector-icons";
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 [modalDivisi, setModalDivisi] = useState(false);
   const [disableBtn, setDisableBtn] = useState(true);
   const [dataMember, setDataMember] = useState<any>([]);
   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);
      } 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 response = await apiEditAnnouncement({
            ...dataForm, user: hasil, groups: dataMember,
         }, 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)
      }
   }

   return (
      <SafeAreaView>
         <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();
                     }}
                  />
               ),
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <InputForm
                  label="Judul"
                  type="default"
                  placeholder="Judul Pengumuman"
                  required
                  error={error.title}
                  errorText="Judul harus diisi"
                  onChange={(val) => validationForm("title", val)}
                  value={dataForm.title}
               />
               <InputForm
                  label="Pengumuman"
                  type="default"
                  placeholder="Deskripsi Pengumuman"
                  required
                  error={error.desc}
                  errorText="Pengumuman harus diisi"
                  onChange={(val) => validationForm("desc", val)}
                  value={dataForm.desc}
                  multiline
               />
               <ButtonSelect
                  value="Pilih divisi penerima pengumuman"
                  onPress={() => {
                     setModalDivisi(true)
                  }}
               />
               {
                  dataMember.length > 0
                  &&
                  <View style={[Styles.borderAll, Styles.round10, Styles.p10]}>
                     {
                        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]}>
                                          <Entypo name="dot-single" size={24} color="black" />
                                          <Text style={[Styles.textDefault]}>{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}
         />
      </SafeAreaView>
   );
}
