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 Text from '@/components/Text';
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, View } from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";


export default function CreateDiscussionGeneral() {
   const { token, decryptToken } = useAuthSession()
   const entityUser = useSelector((state: any) => state.user);
   const userLogin = useSelector((state: any) => state.entities)
   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))
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan data', })
            router.back()
         }else{
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error);
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      }
   }

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => { handleBack() }}
                  />
               ),
               headerTitle: "Tambah Diskusi",
               headerTitleAlign: "center",
               headerRight: () => (
                  <ButtonSaveHeader
                     category="create"
                     disable={disableBtn}
                     onPress={() => {
                        entitiesMember.length == 0
                           ? Toast.show({ type: 'small', text1: 'Anda belum memilih anggota', })
                           : handleCreate()
                     }}
                  />
               ),
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               {
                  (entityUser.role == "supadmin" ||
                     entityUser.role == "developer") && (
                     <SelectForm
                        label="Lembaga Desa"
                        placeholder="Pilih Lembaga Desa"
                        value={chooseGroup.label}
                        required
                        onPress={() => {
                           setValChoose(chooseGroup.val);
                           setValSelect("group");
                           setSelect(true);
                        }}
                        error={error.group}
                        errorText="Lembaga Desa tidak boleh kosong"
                     />
                  )
               }
               <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 (entityUser.role == "supadmin" || entityUser.role == "developer") {
                        if (chooseGroup.val != "") {
                           setSelect(true);
                           setValSelect("member");
                        } else {
                           Toast.show({ type: 'small', text1: 'Pilih Lembaga Desa terlebih dahulu', })
                        }
                     } else {
                        validationForm('group', userLogin.idGroup, userLogin.group);
                        setValChoose(userLogin.idGroup)
                        setSelect(true);
                        setValSelect("member");
                     }

                  }}
               />
               {
                  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>
   );
}
