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 ImageUser from "@/components/imageNew";
import { InputForm } from "@/components/inputForm";
import LoadingCenter from "@/components/loadingCenter";
import MenuItemRow from "@/components/menuItemRow";
import ModalSelect from "@/components/modalSelect";
import SelectForm from "@/components/selectForm";
import Text from '@/components/Text';
import { ConstEnv } from "@/constants/ConstEnv";
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 { useTheme } from "@/providers/ThemeProvider";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import * as DocumentPicker from "expo-document-picker";
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 { colors } = useTheme();
   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 [loading, setLoading] = useState(false)
   const [fileForm, setFileForm] = useState<any[]>([])
   const [isModalFile, setModalFile] = useState(false)
   const [indexDelFile, setIndexDelFile] = useState<number>(0)
   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]);

   useEffect(() => {
      dispatch(setMemberChoose([]))
   }, [])

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

   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) {
      setFileForm([...fileForm.filter((val, i) => i !== index)])
      setModalFile(false)
   }

   async function handleCreate() {
      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, member: entitiesMember }
         ))

         const response = await apiCreateDiscussionGeneral(fd)

         // 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: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal menambahkan data"

         Toast.show({ type: 'small', text1: message })
      } finally {
         setLoading(false)
      }
   }

   return (
      <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => { handleBack() }}
               //    />
               // ),
               headerTitle: "Tambah Diskusi",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonSaveHeader
               //       category="create"
               //       disable={disableBtn || loading ? true : false}
               //       onPress={() => {
               //          entitiesMember.length == 0
               //             ? Toast.show({ type: 'small', text1: 'Anda belum memilih anggota', })
               //             : handleCreate()
               //       }}
               //    />
               // ),
               header: () => (
                  <AppHeader
                     title="Tambah Diskusi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           category="create"
                           disable={disableBtn || loading ? true : false}
                           onPress={() => {
                              entitiesMember.length == 0
                                 ? Toast.show({ type: 'small', text1: 'Anda belum memilih anggota', })
                                 : handleCreate()
                           }}
                        />
                     }
                  />
               )
            }}
         />
         {loading && <LoadingCenter />}
         <ScrollView showsVerticalScrollIndicator={false} style={[Styles.h100, Styles.flex1, { backgroundColor: colors.background }]}>
            <View style={[Styles.p15, Styles.mb100]}>
               {
                  (entityUser.role == "supadmin" ||
                     entityUser.role == "developer") && (
                     <SelectForm
                        label="Lembaga Desa"
                        placeholder="Pilih Lembaga Desa"
                        value={chooseGroup.label}
                        required
                        bg={colors.card}
                        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}
                  bg={colors.card}
                  errorText="Judul tidak boleh kosong"
                  onChange={(val) => { validationForm("title", val) }}
               />
               <InputForm
                  label="Diskusi"
                  type="default"
                  placeholder="Hal yang didiskusikan"
                  required
                  error={error.desc}
                  bg={colors.card}
                  errorText="Diskusi tidak boleh kosong"
                  onChange={(val) => { validationForm("desc", val) }}
                  multiline
               />
               <ButtonSelect value="Upload File" onPress={pickDocumentAsync} />
               {
                  fileForm.length > 0
                  &&
                  <>
                     <View style={[Styles.rowSpaceBetween, Styles.mv05]}>
                        <Text style={[Styles.textDefaultSemiBold]}>File</Text>
                        <Text style={[Styles.textDefault]}>{fileForm.length} file</Text>
                     </View>
                     <View style={[Styles.borderAll, Styles.round05, Styles.p10, Styles.mb10, { backgroundColor: colors.card, borderColor: colors.icon + '20' }]}>
                        {
                           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}
                                 bgColor="transparent"
                                 titleWeight="normal"
                                 onPress={() => { setIndexDelFile(index); setModalFile(true) }}
                              />
                           ))
                        }
                     </View>
                  </>
               }
               <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 style={[Styles.textDefaultSemiBold]}>Anggota</Text>
                        <Text style={[Styles.textDefault]}>{entitiesMember.length} Anggota</Text>
                     </View>

                     <View style={[Styles.borderAll, Styles.round05, Styles.p10, { backgroundColor: colors.card, borderColor: colors.icon + '20' }]}>
                        {
                           entitiesMember.map((item: { img: any; name: any; }, index: any) => {
                              return (
                                 <BorderBottomItem
                                    key={index}
                                    borderType={entitiesMember.length - 1 == index ? "none" : "bottom"}
                                    icon={
                                       <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} size="xs" />
                                    }
                                    title={item.name}
                                    bgColor="transparent"
                                 />
                              )
                           })
                        }
                     </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}
         />

         <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) }}
               />
            </View>
         </DrawerBottom>
      </SafeAreaView>
   );
}
