import React, { useContext, useEffect, useState } from "react";
import { Box, Button, Text, useToast } from "@chakra-ui/react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useNavigate, useParams } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
import { ArrowBackIcon } from "@chakra-ui/icons";
import { OPACITY_ON_LOAD } from "../../Layout/animations";
import FormInputMain from "../../Components/FormInputMain";
import ToastBox from "../../Components/ToastBox";
import FullscreenLoaders from "../../Components/Loaders/FullscreenLoaders";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import RoleSwitchButton from "../../Components/RoleSwitchButton";
import {
  useCreateSubAdminMutation,
  useGetSubAdminByIdQuery,
  useUpdateSubAdminMutation,
} from "../../Services/subadmin.service";
import { useGetSponserByIdQuery } from "../../Services/io.service";
// ======================= [validation] =========================

export const addSubAdmin = yup.object().shape({
  firstName: yup
    .string()
    .required("First Name is required")
    .min(3, "First Name must be at least 3 characters long")
    .max(50, "First Name cannot exceed 50 characters")
    .matches(/^[^\d]+$/, "First Name cannot contain numbers"),

    lastName: yup
    .string()
    .required("Last Name name in arabic is required"),
    emailAddress: yup.string().email("Invalid email address").notRequired(),
  //   .test("emailValidity", "Email address is invalid", async function (value) {
  //     if (!value) {
  //         return true; // Allow if the field is empty
  //     }
  //     return await checkEmailValidity(value);
  // }),
});

// ==================== [debounce] ========================

export function debounce(func, delay) {
  let debounceTimer;
  return function (...args) {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => func.apply(this, args), delay);
  };
}

const SubAdminUpdateCreate = () => {
  const toast = useToast();
  const params = useParams();
  const navigate = useNavigate();
  const id = params?.id;

  // =====================[useState]=======================

  const [isLoadingBtn, setIsLoadingBtn] = useState(false);
  const [alert, setAlert] = useState(false);
  const [form, setForm] = useState();
  const [isSwitchOn, setIsSwitchOn] = useState(true);

  const [createSubAdmin] = useCreateSubAdminMutation();
  const [updateSubAdmin] = useUpdateSubAdminMutation();

  // Fetch sponsor data only if id exists
  const {
    data: subAdminByIdData,
    error,
    isLoading,
  } = useGetSubAdminByIdQuery(id, { skip: !id });

  // ======================== [validators] ===========================

  const {
    control,
    watch,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: yupResolver(addSubAdmin),
  });

  // ========================== [useEffect] ================================

  useEffect(() => {
    if (subAdminByIdData?.data) {
      reset({
        firstName: subAdminByIdData?.data?.firstName,
        lastName: subAdminByIdData?.data?.lastName,
        emailAddress: subAdminByIdData?.data?.emailAddress,
      });
      setIsSwitchOn(subAdminByIdData?.data?.role[0]?.role==="Maker");
      console.log(subAdminByIdData?.data?.role);
    }
  }, [subAdminByIdData, reset]);


  if (false) {
    return <FullscreenLoaders />;
  }

  // ============================ [API]===============================


  const handleConfirm = async () => {
    setIsLoadingBtn(true);
    const id = params?.id;
    console.log(isSwitchOn);
    
    if (id) {
      try {
        const formData = {
          ...form,
          role_xid: isSwitchOn?2:1,
        };
        await updateSubAdmin({ data: formData, id }).then((response) => {
          if (response?.data?.statusCode) {
            toast({
              render: () => <ToastBox message={response?.data?.message} />,
            });

            setIsLoadingBtn(false);
            setAlert(false);
            navigate("/subadmin");
          } else if (response?.error?.status === 400) {
            toast({
              render: () => (
                <ToastBox
                  message={response?.error?.data?.message}
                  status={"error"}
                />
              ),
            });

            setIsLoadingBtn(false);
            setAlert(false);
          }
        });
      } catch (error) {
        console.log(error);
        setIsLoadingBtn(false);
        navigate("/subadmin");
      }
    } else {
      try {
        const formData = {
          ...form,
          role_xid: isSwitchOn?2:1,
        };
        await createSubAdmin(formData).then((response) => {
          console.log(response);
          if (response?.data?.statusCode === 201) {
            toast({
              render: () => <ToastBox message={response?.data?.message} />,
            });

            setIsLoadingBtn(false);
            navigate("/subadmin");
          } else if (response?.error?.status === 400) {
            toast({
              render: () => (
                <ToastBox
                  message={response?.error?.data?.message}
                  status={"error"}
                />
              ),
            });

            setIsLoadingBtn(false);
            setAlert(false);
          }
        });
      } catch (error) {
        console.log(error);

        setIsLoadingBtn(false);
        navigate("/subadmin");
      }
    }
  };

  // ====================== [Update  Form Object] =========================

  const formFields = [
    {
      label: "First Name",
      placeHolder: " ",
      name: "firstName",
      type: "text",
      isRequired: true,
      section: "",
      maxLength: 50,
      helperText: `Maximum length should be 50 characters. You have entered ${
        watch()?.firstName?.length || 0
      } characters.`,
    },
    {
      label: "Last Name",
      name: "lastName",
      placeHolder: " ",
      type: "text",
      isRequired: true,
      section: "",
      arabic: true,
      right: true,
      maxLength: 55,
      helperText: `Maximum length should be 55 characters. You have entered ${
        watch()?.lastName?.length || 0
      } characters.`,
    },
    {
      label: "Email address",
      name: "emailAddress",
      placeHolder: " ",
      type: "email",
      // isRequired: true,
      section: "",
    },
  ];

  // ==================== [Create Form Object] =======================

  const formEditFields = [
    {
      label: "First Name",
      placeHolder: " ",
      name: "firstName",
      type: "text",
      isRequired: true,
      section: "",
      maxLength: 55,
      helperText: `Maximum length should be 55 characters. You have entered ${
        watch()?.firstName?.length || 0
      } characters.`,
    },
    {
      label: "Last Name",
      name: "lastName",
      placeHolder: " ",
      type: "text",
      isRequired: true,
      section: "",
      arabic: true,
      maxLength: 55,
      helperText: `Maximum length should be 55 characters. You have entered ${
        watch()?.lastName?.length || 0
      } characters.`,
    },
    {
      label: "Email Address",
      name: "emailAddress",
      placeHolder: " ",
      type: "email",
      // isRequired: true,
      section: "",
    },
  ];

  // ====================== [Group Create Fields] =========================

  const groupedEditFields = formEditFields.reduce((groups, field) => {
    const { section } = field;
    if (!groups[section]) {
      groups[section] = [];
    }
    groups[section].push(field);
    return groups;
  }, {});

  // ====================== [Group Update Fields] =======================

  const groupedFields = formFields.reduce((groups, field) => {
    const { section } = field;
    if (!groups[section]) {
      groups[section] = [];
    }
    groups[section].push(field);
    return groups;
  }, {});

  // ==================== [On Submit] ========================
console.log(errors);

  const onSubmit = async (data) => {
    console.log("Hit");
    
    if (Object.keys(errors).length === 0) {
      setForm(data);
      setAlert(true);
    }
  };

  return isLoading ? (
    <FullscreenLoaders />
  ) : (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={14}>
      {/* =====================  [Switch Button] ======================== */}
      <Box
        display={"flex"}
        justifyContent={"space-between"}
        alignItems={"center"}
        mt={5}
        px={4}
      >
        <Text
          fontSize={"sm"}
          mb={0}
          onClick={() => navigate(-1)}
          cursor={"pointer"}
        >
          <ArrowBackIcon fontSize={"xl"} me={2} />
          Add Details
        </Text>
        <RoleSwitchButton
          isSwitchOn={isSwitchOn}
          setIsSwitchOn={setIsSwitchOn}
        />
      </Box>

      {/* ====================== [Form Input] ====================== */}

      <FormInputMain
        groupedFields={params?.id ? groupedEditFields : groupedFields}
        control={control}
        errors={errors}
        onSubmit={handleSubmit(onSubmit)}
        submitTitle={params?.id ? "Update" : "Submit"}
      ></FormInputMain>

      {/* ======================= [Modal] =========================== */}

      <CustomAlertDialog
        isOpen={alert}
        onClose={() => setAlert(false)}
        alertHandler={handleConfirm}
        message={
          id
            ? "Are you sure you want to update this?"
            : "Are you sure you want to add this?"
        }
        isLoading={isLoadingBtn}
      />

      {/* <DummyComponent /> */}
    </Box>
  );
};

export default SubAdminUpdateCreate;
