import React, { useContext, useEffect, useState } from "react";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
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 FormInputMain from "../../../Components/FormInputMain";
import SwitchButton from "../../../Components/SwitchButton";
import {
  useCreateInvestmentTypeMutation,
  useGetInvestmentTypeByIdQuery,
  useUpdateInvestmentTypeMutation,
} from "../../../Services/io.service";
import ToastBox from "../../../Components/ToastBox";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";
import { ArrowBackIcon } from "@chakra-ui/icons";

// ======================= [validation] =========================

export const addInvestmentType = yup.object().shape({
  investmentTypeName: yup
    .string()
    .required("Investment type is required")
    .max(50, "Investment name cannot be more than 50 characters"),
  // note: yup.string().optional().max(255, "Note cannot exceed 255 characters"),
  investmentTypeNameArabic: yup
    .string()
    .required("Investment type in required"),
  noteArabic: yup.string().notRequired(),
});

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

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

const AddInvestmentType = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const params = useParams();
  const id = params?.id;
  console.log("hit");

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

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

  const [createInvestmentType] = useCreateInvestmentTypeMutation();
  const [updateInvestmentType] = useUpdateInvestmentTypeMutation();

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

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

  const {
    data: investmentTypeByIdData,
    error,
    isLoading,
  } = useGetInvestmentTypeByIdQuery(id, { skip: !id });

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

  useEffect(() => {
    if (investmentTypeByIdData?.data) {
      reset({
        investmentTypeName: investmentTypeByIdData?.data?.investmentTypeName,
        investmentTypeNameArabic:
          investmentTypeByIdData?.data?.investmentTypeNameArabic,
        note: investmentTypeByIdData?.data?.note,
        noteArabic: investmentTypeByIdData?.data?.noteArabic,
      });
      setIsSwitchOn(investmentTypeByIdData?.data?.isActive);
    }
  }, [investmentTypeByIdData, reset]);

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

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

  const handleConfirm = async () => {
    setIsLoadingBtn(true);
    const id = params?.id;
    if (id) {
      try {
        const formData = {
          ...form,
          isActive: isSwitchOn,
        };
        await updateInvestmentType({ data: formData, id }).then((response) => {
          if (response?.data?.statusCode === 200) {
            toast({
              render: () => <ToastBox message={response?.data?.message} />,
            });

            setIsLoadingBtn(false);
            setAlert(false);
            navigate("/investment-type");
          } else {
            toast({
              render: () => (
                <ToastBox message={"Something Went Wrong"} status={"error"} />
              ),
            });

            setIsLoadingBtn(false);
            navigate("/investment-type");
          }
        });
      } catch (error) {
        console.log(error);
        setIsLoadingBtn(false);
        navigate("/investment-type");
      }
    } else {
      try {
        const formData = {
          ...form,
          isActive: isSwitchOn,
        };

        await createInvestmentType(formData).then((response) => {
          if (response?.data?.statusCode === 201) {
            toast({
              render: () => <ToastBox message={response?.data?.message} />,
            });

            setIsLoadingBtn(false);
            navigate("/investment-type");
          } else {
            toast({
              render: () => (
                <ToastBox message={"Something Went Wrong"} status={"error"} />
              ),
            });

            setIsLoadingBtn(false);
            navigate("/investment-type");
          }
        });
      } catch (error) {
        console.log(error);

        setIsLoadingBtn(false);
        navigate("/investment-type");
      }
    }
  };

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

  const formFields = [
    {
      label: "Investment Type (English)",
      placeHolder: " ",
      name: "investmentTypeName",
      type: "text",
      isRequired: true,
      section: "",
      maxLength: 50,
      helperText: `Maximum length should be 50 characters. You have entered ${
        watch()?.investmentTypeName?.length || 0
      } characters.`,
    },
    {
      label: "Investment Type (Arabic) ",
      name: "investmentTypeNameArabic",
      placeHolder: " ",
      type: "text",
      isRequired: true,
      section: "",
      arabic: true,
      maxLength: 255,
      helperText: `Maximum length should be 255 characters. You have entered ${
        watch()?.investmentTypeNameArabic?.length || 0
      } characters.`,
    },
    {
      label: "Description (English)",
      placeHolder: " ",
      name: "note",
      type: "textarea",
      isRequired: false,
      section: "",
      maxLength: 255,
      helperText: `Maximum length should be 255 characters. You have entered ${
        watch()?.note?.length || 0
      } characters.`,
    },
    {
      label: "Description (Arabic)",
      placeHolder: " ",
      name: "noteArabic",
      type: "textarea",
      isRequired: false,
      arabic: true,
      section: "",
      maxLength: 255,
      helperText: `Maximum length should be 255 characters. You have entered ${
        watch()?.noteArabic?.length || 0
      } characters.`,
    },
  ];

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

  const formEditFields = [
    {
      label: "Investment Type (English)",
      placeHolder: " ",
      name: "investmentTypeName",
      type: "text",
      isRequired: true,
      section: "",
      maxLength: 50,
      helperText: `Maximum length should be 50 characters. You have entered ${
        watch()?.investmentTypeName?.length || 0
      } characters.`,
    },
    {
      label: "Investment Type (Arabic)",
      name: "investmentTypeNameArabic",
      placeHolder: " ",
      type: "text",
      isRequired: true,
      section: "",
      arabic: true,
      maxLength: 255,
      helperText: `Maximum length should be 255 characters. You have entered ${
        watch()?.investmentTypeNameArabic?.length || 0
      } characters.`,
    },
    {
      label: "Description (English)",
      placeHolder: " ",
      name: "note",
      type: "textarea",
      isRequired: false,
      section: "",
      maxLength: 255,
      helperText: `Maximum length should be 255 characters. You have entered ${
        watch()?.note?.length || 0
      } characters.`,
    },
    {
      label: "Description (Arabic)",
      placeHolder: " ",
      name: "noteArabic",
      type: "textarea",
      isRequired: false,
      arabic: true,
      section: "",
      maxLength: 255,
      helperText: `Maximum length should be 255 characters. You have entered ${
        watch()?.noteArabic?.length || 0
      } characters.`,
    },
  ];

  // ====================== [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] ========================

  const onSubmit = async (data) => {
    // setIsLoadingBtn(true);
    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} mb={5}>
        <Text fontSize={"sm"} mb={0}  onClick={() => navigate(-1)} cursor={"pointer"}>
          <ArrowBackIcon fontSize={"xl"} me={2} />{params?.id ? "Edit Details" : "Add Details"}
        </Text>
        <SwitchButton 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"}
        // btnLoading={isLoadingBtn}
      ></FormInputMain>

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

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

export default AddInvestmentType;
