import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import ModalSelect from "@/components/modalSelect";
import SelectForm from "@/components/selectForm";
import Text from "@/components/Text";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiCreateUser } from "@/lib/api";
import { setUpdateMember } from "@/lib/memberSlice";
import { useAuthSession } from "@/providers/AuthProvider";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import * as ImagePicker from "expo-image-picker";
import { router, Stack } from "expo-router";
import { useEffect, useState } from "react";
import {
   Image,
   Pressable,
   SafeAreaView,
   ScrollView,
   View
} from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";

export default function CreateMember() {
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.memberUpdate)
   const { token, decryptToken } = useAuthSession()
   const [valSelect, setValSelect] = useState<"group" | "position" | "role" | "gender">("group");
   const [chooseGroup, setChooseGroup] = useState({ val: "", label: "" });
   const [choosePosition, setChoosePosition] = useState({ val: "", label: "" });
   const [chooseRole, setChooseRole] = useState({ val: "", label: "" });
   const [chooseGender, setChooseGender] = useState({ val: "", label: "" });
   const [selectedImage, setSelectedImage] = useState<string | undefined>(undefined);
   const entityUser = useSelector((state: any) => state.user);
   const [isSelect, setSelect] = useState(false);
   const [disableBtn, setDisableBtn] = useState(true)
   const [valChoose, setValChoose] = useState("")
   const [imgForm, setImgForm] = useState<any>()
   const [error, setError] = useState({
      group: false,
      position: false,
      nik: false,
      name: false,
      phone: false,
      email: false,
      gender: false,
      role: false,
   });
   const [dataForm, setDataForm] = useState({
      idGroup: "",
      idPosition: "",
      idUserRole: "",
      nik: "",
      name: "",
      phone: "",
      email: "",
      gender: "",
   });

   function validationForm(cat: string, val: any, label?: string) {
      if (cat == "group") {
         setChooseGroup({ val, label: String(label) });
         setChoosePosition({ val: "", label: "" });
         setDataForm({ ...dataForm, idGroup: val, idPosition: "" });
         if (val == "" || val == "null") {
            setError({ ...error, group: true });
         } else {
            setError({ ...error, group: false });
         }
      } else if (cat == "position") {
         setChoosePosition({ val, label: String(label) });
         setDataForm({ ...dataForm, idPosition: val });
         if (val == "" || val == "null") {
            setError({ ...error, position: true });
         } else {
            setError({ ...error, position: false });
         }
      } else if (cat == "role") {
         setChooseRole({ val, label: String(label) });
         setDataForm({ ...dataForm, idUserRole: val });
         if (val == "" || val == "null") {
            setError({ ...error, role: true });
         } else {
            setError({ ...error, role: false });
         }
      } else if (cat == "nik") {
         setDataForm({ ...dataForm, nik: val });
         if (val == "" || val.length !== 16) {
            setError({ ...error, nik: true });
         } else {
            setError({ ...error, nik: false });
         }
      } else if (cat == "name") {
         setDataForm({ ...dataForm, name: val });
         if (val == "") {
            setError({ ...error, name: true });
         } else {
            setError({ ...error, name: false });
         }
      } else if (cat == "email") {
         setDataForm({ ...dataForm, email: val });
         if (
            val == "" ||
            !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(val)
         ) {
            setError({ ...error, email: true });
         } else {
            setError({ ...error, email: false });
         }
      } else if (cat == "phone") {
         setDataForm({ ...dataForm, phone: val });
         if (val == "" || !(val.length >= 10 && val.length <= 15)) {
            setError({ ...error, phone: true });
         } else {
            setError({ ...error, phone: false });
         }
      } else if (cat == "gender") {
         setChooseGender({ val, label: String(label) });
         setDataForm({ ...dataForm, gender: val });
         if (val == "" || val == "null") {
            setError({ ...error, gender: true });
         } else {
            setError({ ...error, gender: false });
         }
      }

   }

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

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


   async function handleCreate() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const fd = new FormData()

         fd.append("data", JSON.stringify(
            { user: hasil, ...dataForm }
         ))

         if (imgForm != undefined) {
            fd.append("file", {
               uri: imgForm.uri,
               type: imgForm.mimeType,
               name: imgForm.fileName,
            } as any)
         } else {
            fd.append("file", "undefined")
         }

         const response = await apiCreateUser(fd)
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan data', })
            dispatch(setUpdateMember(!update))
            router.back()
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error)
      }
   }


   const pickImageAsync = async () => {
      let result = await ImagePicker.launchImageLibraryAsync({
         mediaTypes: ["images"],
         allowsEditing: true,
         quality: 1,
         aspect: [1, 1],
      });

      if (!result.canceled) {
         setSelectedImage(result.assets[0].uri);
         setImgForm(result.assets[0]);

      } else {
         alert("Tidak ada gambar yang dipilih");
      }
   };

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => {
                        router.back();
                     }}
                  />
               ),
               headerTitle: "Tambah Anggota",
               headerTitleAlign: "center",
               headerRight: () => (
                  <ButtonSaveHeader
                     disable={disableBtn}
                     category="create"
                     onPress={() => { handleCreate() }}
                  />
               ),
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <View style={{ justifyContent: "center", alignItems: "center" }}>
                  {selectedImage != undefined ? (
                     <Pressable onPress={pickImageAsync}>
                        <Image src={selectedImage} style={[Styles.userProfileBig]} />
                     </Pressable>
                  ) : (
                     <Pressable
                        onPress={pickImageAsync}
                        style={[Styles.iconContent, ColorsStatus.gray]}
                     >
                        <MaterialCommunityIcons
                           name="account-tie"
                           size={100}
                           color={"gray"}
                        />
                     </Pressable>
                  )}
               </View>
               {(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"
                     />
                  )}
               <SelectForm
                  label="Jabatan"
                  placeholder="Pilih Jabatan"
                  value={choosePosition.label}
                  required
                  onPress={() => {
                     setValChoose(choosePosition.val);
                     setValSelect("position");
                     setSelect(true);
                  }}
                  error={error.position}
                  errorText="Jabatan tidak boleh kosong"
               />
               <SelectForm
                  label="User Role"
                  placeholder="Pilih Role"
                  value={chooseRole.label}
                  required
                  onPress={() => {
                     setValChoose(chooseRole.val);
                     setValSelect("role");
                     setSelect(true);
                  }}
                  error={error.role}
                  errorText="Role tidak boleh kosong"
               />
               <InputForm
                  label="NIK"
                  type="numeric"
                  placeholder="NIK"
                  required
                  error={error.nik}
                  errorText="NIK Harus 16 Karakter"
                  onChange={val => {
                     validationForm("nik", val)
                  }}
               />
               <InputForm
                  label="Nama"
                  type="default"
                  placeholder="Nama"
                  required
                  error={error.name}
                  errorText="Nama tidak boleh kosong"
                  onChange={val => {
                     validationForm("name", val)
                  }}
               />
               <InputForm
                  label="Email"
                  type="default"
                  placeholder="Email"
                  required
                  error={error.email}
                  errorText="Email tidak valid"
                  onChange={val => {
                     validationForm("email", val)
                  }}
               />
               <InputForm
                  label="Nomor Telepon"
                  type="numeric"
                  placeholder="8XX-XXX-XXX"
                  required
                  itemLeft={<Text>+62</Text>}
                  error={error.phone}
                  errorText="Nomor Telepon tidak valid"
                  onChange={val => {
                     validationForm("phone", val)
                  }}
               />
               <SelectForm
                  label="Jenis Kelamin"
                  placeholder="Pilih Jenis Kelamin"
                  value={chooseGender.label}
                  required
                  onPress={() => {
                     setValChoose(chooseGender.val);
                     setValSelect("gender");
                     setSelect(true);
                  }}
                  error={error.gender}
                  errorText="Jenis Kelamin tidak boleh kosong"
               />
            </View>
         </ScrollView>

         <ModalSelect
            category={valSelect}
            close={setSelect}
            onSelect={(value) => {
               validationForm(valSelect, value.val, value.label);
            }}
            title={
               valSelect == "group"
                  ? "Lembaga Desa"
                  : valSelect == "position"
                     ? "Jabatan"
                     : valSelect == "role"
                        ? "User Role"
                        : "Jenis Kelamin"
            }
            open={isSelect}
            idParent={valSelect == "position" ? chooseGroup.val : ""}
            valChoose={valChoose}
         />
      </SafeAreaView>
   );
}
