import AppHeader from "@/components/AppHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import LoadingCenter from "@/components/loadingCenter";
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 { validateName } from "@/lib/fun_validateName";
import { setUpdateMember } from "@/lib/memberSlice";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { useHeaderHeight } from '@react-navigation/elements';
import * as ImagePicker from "expo-image-picker";
import { router, Stack } from "expo-router";
import { useEffect, useState } from "react";
import {
   Image,
   KeyboardAvoidingView,
   Platform,
   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 headerHeight = useHeaderHeight();
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.memberUpdate)
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   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 entities = useSelector((state: any) => state.entities)
   const [isSelect, setSelect] = useState(false);
   const [disableBtn, setDisableBtn] = useState(true)
   const [valChoose, setValChoose] = useState("")
   const [imgForm, setImgForm] = useState<any>()
   const [loading, setLoading] = useState(false)
   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 (!validateName(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 >= 9 && val.length <= 16)) {
            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])

   useEffect(() => {
      if (entityUser.role != "supadmin" && entityUser.role != "developer") {
         validationForm("group", entities.idGroup, entities.group)
      }
   }, [])


   async function handleCreate() {
      try {
         setLoading(true)
         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 || "image/jpeg",
               name: imgForm.fileName || "image.jpg",
            } as any)
         } else {
            fd.append("file", "undefined")
         }

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

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


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

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

   return (
      <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
         <Stack.Screen
            options={{
               headerTitle: "Tambah Anggota",
               headerTitleAlign: "center",
               header: () => (
                  <AppHeader title="Anggota"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={disableBtn || loading}
                           category="create"
                           onPress={() => { handleCreate() }}
                        />
                     }
                  />
               )
            }}
         />
         {loading && <LoadingCenter />}
         <KeyboardAvoidingView
            style={[Styles.h100, { backgroundColor: colors.background }]}
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={headerHeight}
         >
            <ScrollView showsVerticalScrollIndicator={false}>
               <View style={[Styles.p15]}>
                  <View style={[Styles.contentItemCenter]}>
                     {selectedImage != undefined ? (
                        <Pressable onPress={pickImageAsync}>
                           <Image src={selectedImage} style={[Styles.userProfileBig]} />
                           <View style={[Styles.absoluteIconPicker]}>
                              <MaterialCommunityIcons name="image" color={'white'} size={15} />
                           </View>
                        </Pressable>
                     ) : (
                        <Pressable onPress={pickImageAsync} style={[Styles.iconContent, ColorsStatus.gray]} >
                           <MaterialCommunityIcons name="account-tie" size={85} color={"gray"} />
                           <View style={[Styles.absoluteIconPicker]}>
                              <MaterialCommunityIcons name="image" color={'white'} size={15} />
                           </View>
                        </Pressable>
                     )}
                  </View>
                  {(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"
                        />
                     )}
                  <SelectForm
                     label="Jabatan"
                     placeholder="Pilih Jabatan"
                     value={choosePosition.label}
                     required
                     bg={colors.card}
                     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
                     bg={colors.card}
                     onPress={() => {
                        setValChoose(chooseRole.val);
                        setValSelect("role");
                        setSelect(true);
                     }}
                     error={error.role}
                     errorText="Role tidak boleh kosong"
                  />
                  <InputForm
                     label="NIK"
                     type="numeric"
                     placeholder="NIK"
                     required
                     bg={colors.card}
                     error={error.nik}
                     errorText="NIK Harus 16 Karakter"
                     onChange={val => {
                        validationForm("nik", val)
                     }}
                  />
                  <InputForm
                     label="Nama"
                     type="default"
                     placeholder="Nama"
                     required
                     bg={colors.card}
                     error={error.name}
                     errorText="Nama harus 3–50 karakter (huruf, angka, spasi, dan simbol ringan (. , ' _ -))"
                     onChange={val => {
                        validationForm("name", val)
                     }}
                  />
                  <InputForm
                     label="Email"
                     type="default"
                     placeholder="Email"
                     required
                     bg={colors.card}
                     error={error.email}
                     errorText="Email tidak valid"
                     onChange={val => {
                        validationForm("email", val)
                     }}
                  />
                  <InputForm
                     label="Nomor Telepon"
                     type="numeric"
                     placeholder="8XX-XXX-XXX"
                     required
                     bg={colors.card}
                     itemLeft={<Text style={[Platform.OS === 'ios' && Styles.mt02, { color: colors.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
                     bg={colors.card}
                     onPress={() => {
                        setValChoose(chooseGender.val);
                        setValSelect("gender");
                        setSelect(true);
                     }}
                     error={error.gender}
                     errorText="Jenis Kelamin tidak boleh kosong"
                  />
               </View>
            </ScrollView>
         </KeyboardAvoidingView>


         <ModalSelect
            category={valSelect}
            close={() => { setSelect(false) }}
            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>
   );
}
