import BorderBottomItem from "@/components/borderBottomItem";
import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import ButtonSelect from "@/components/buttonSelect";
import ImageUser from "@/components/imageNew";
import { InputForm } from "@/components/inputForm";
import ModalSelect from "@/components/modalSelect";
import SelectForm from "@/components/selectForm";
import Styles from "@/constants/Styles";
import { apiCreateDiscussionGeneral } from "@/lib/api";
import { setUpdateDiscussionGeneralDetail } from "@/lib/discussionGeneralDetail";
import { setMemberChoose } from "@/lib/memberChoose";
import { useAuthSession } from "@/providers/AuthProvider";
import { router, Stack } from "expo-router";
import { useEffect, useState } from "react";
import { SafeAreaView, ScrollView, Text, ToastAndroid, View } from "react-native";
import { useDispatch, useSelector } from "react-redux";


export default function CreateDiscussionGeneral() {
   const { token, decryptToken } = useAuthSession()
   const [chooseGroup, setChooseGroup] = useState({ val: "", label: "" });
   const [valChoose, setValChoose] = useState("")
   const [valSelect, setValSelect] = useState<"group" | "member">("group");
   const dispatch = useDispatch()
   const [disableBtn, setDisableBtn] = useState(true);
   const [isSelect, setSelect] = useState(false);
   const entitiesMember = useSelector((state: any) => state.memberChoose)
   const update = useSelector((state: any) => state.discussionGeneralDetailUpdate)
   const [dataForm, setDataForm] = useState({
      idGroup: "",
      title: "",
      desc: "",
   });
   const [error, setError] = useState({
      group: false,
      title: false,
      desc: false,
   });

   function validationForm(cat: string, val: any, label?: string) {
      if (cat == "group") {
         setChooseGroup({ val, label: String(label) });
         dispatch(setMemberChoose([]))
         setDataForm({ ...dataForm, idGroup: val });
         if (val == "" || val == "null") {
            setError({ ...error, group: true });
         } else {
            setError({ ...error, group: false });
         }
      } else 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]);


   function handleBack() {
      dispatch(setMemberChoose([]))
      router.back()
   }

   async function handleCreate() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiCreateDiscussionGeneral({
            data: { ...dataForm, user: hasil, member: entitiesMember },
         })
         if (response.success) {
            dispatch(setMemberChoose([]))
            dispatch(setUpdateDiscussionGeneralDetail(!update))
            ToastAndroid.show('Berhasil menambahkan data', ToastAndroid.SHORT)
            router.back()
         }
      } catch (error) {
         console.error(error);
      }
   }

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => { handleBack() }}
                  />
               ),
               headerTitle: "Tambah Diskusi",
               headerTitleAlign: "center",
               headerRight: () => (
                  <ButtonSaveHeader
                     category="create"
                     disable={disableBtn}
                     onPress={() => {
                        entitiesMember.length == 0
                           ? ToastAndroid.show(
                              "Anda belum memilih anggota",
                              ToastAndroid.SHORT
                           )
                           : handleCreate()
                     }}
                  />
               ),
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <SelectForm
                  label="Lembaga Desa"
                  placeholder="Pilih Lembaga Desa"
                  value={chooseGroup.label}
                  required
                  onPress={() => {
                     setValChoose(chooseGroup.val);
                     setValSelect("group");
                     setSelect(true);
                  }}
               />
               <InputForm
                  label="Judul"
                  type="default"
                  placeholder="Judul"
                  required
                  error={error.title}
                  errorText="Judul tidak boleh kosong"
                  onChange={(val) => { validationForm("title", val) }}
               />
               <InputForm
                  label="Diskusi"
                  type="default"
                  placeholder="Hal yang didiskusikan"
                  required
                  error={error.desc}
                  errorText="Diskusi tidak boleh kosong"
                  onChange={(val) => { validationForm("desc", val) }}
               />
               <ButtonSelect
                  value="Pilih Anggota"
                  onPress={() => {
                     if (chooseGroup.val != "") {
                        setSelect(true);
                        setValSelect("member");
                     } else {
                        ToastAndroid.show(
                           "Pilih Lembaga Desa terlebih dahulu",
                           ToastAndroid.SHORT
                        );
                     }
                  }}
               />
               {
                  entitiesMember.length > 0 &&
                  <View>
                     <View style={[Styles.rowSpaceBetween, Styles.mv05]}>
                        <Text>Anggota</Text>
                        <Text>Total {entitiesMember.length} Anggota</Text>
                     </View>

                     <View style={[Styles.borderAll, Styles.round10, Styles.p10]}>
                        {
                           entitiesMember.map((item: { img: any; name: any; }, index: any) => {
                              return (
                                 <BorderBottomItem
                                    key={index}
                                    borderType="bottom"
                                    icon={
                                       <ImageUser src={`https://wibu-storage.wibudev.com/api/files/${item.img}`} size="sm" />
                                    }
                                    title={item.name}
                                 />
                              )
                           })
                        }
                     </View>
                  </View>
               }
            </View>
         </ScrollView>

         <ModalSelect
            category={valSelect}
            close={setSelect}
            onSelect={(value) => {
               validationForm(valSelect, value.val, value.label);
            }}
            title={valSelect == "group" ? "Lembaga Desa" : "Pilih Anggota"}
            open={isSelect}
            idParent={valSelect == "member" ? chooseGroup.val : ""}
            valChoose={valChoose}
         />
      </SafeAreaView>
   );
}
