import ValidationField from "../../../../Components/ValidationField/ValidationField";
import { useFormikContext } from "formik";
import { useModalState } from "../../../../zustand/Modal";
import { useObjectToEdit } from "../../../../zustand/ObjectToEditState";
import { useTranslation } from "react-i18next";
import { QueryStatusEnum } from "../../../../enums/QueryStatus";
import { Button, Divider, Spin } from "antd";
import { MdCancel } from "react-icons/md";
import { useAddSales } from "../../../../api/sales";
import { useEffect } from "react";
import { toast } from "react-toastify";
import { ModalBodyProps } from "../../../../types/Sales";
import { useQueryClient } from "react-query";
import { onEnterDown } from "../../../../utils/onKeyDown";
import { ModalEnum } from "../../../../enums/Model";

const Form = ({ handleCloseModel = () => {} }: ModalBodyProps) => {
  const { setObjectToEdit, objectToEdit } = useObjectToEdit();
  const { values, setFieldValue } = useFormikContext<any>();
  const formik = useFormikContext();
  const { setIsOpen } = useModalState((state) => state);
  const queryClient = useQueryClient();
  const { t } = useTranslation();


  const { mutate, status, error, reset }: any = useAddSales();
  const coupon_id_object = objectToEdit?.data?.data?.packages.find(
    (e: any) => e.id === values?.package_id,
  );
  const student_info = objectToEdit?.data?.data;
  const PackagesInfo = student_info?.packages.map((info: any) => ({
    id: info?.id,
    name:(
      <div>
        {info.name } ( <span className={`${info?.coupon_id !== null && 'removed_sales disapled'}`}>{info?.original_price.toLocaleString("en-US")}</span> ) 
        {info?.coupon_id !== null && <span className="new_sales disapled"> {info?.final_price.toLocaleString("en-US")}</span>}
        </div>
        ),
  }));

  const handleNext = () => {
    mutate({
      package_id: values?.package_id,
      student_id: objectToEdit?.data?.data?.student_id,
      coupon_id: coupon_id_object?.coupon_id,
    });
  };
  useEffect(() => {
    if (status === QueryStatusEnum.SUCCESS) {
      reset();
    } else if (status === QueryStatusEnum.ERROR) {
      toast.error(
        t(
          `toast.${error?.response?.data?.message}` ||
            `toast.error_while_trying_please_try_again`,
        ),
      );
    }


  }, [ status]);

  useEffect(() =>{
    if (values?.currentModalIndex >= 3) {
      setIsOpen("");
      setObjectToEdit({});
      setFieldValue("currentModalIndex", 0);
      queryClient.resetQueries();
      reset();
    }
  })
const isDisabled = status === QueryStatusEnum.LOADING

  const handleKeyDown = (e:any) =>{
    onEnterDown(e,handleNext,isDisabled)
  }
  
  const handleAddAnotherPurchase = () =>{
    handleCloseModel("")
    setIsOpen(ModalEnum.Sales_ADD)
  }

  return (
    values?.currentModalIndex == 2 && (
      <div className="w-100">
        <header className="modal_title">
          <span>{t(`models.are_you_sure_about_sale`)} </span>
          <MdCancel onClick={handleCloseModel} />
        </header>

        <Divider />
        <div className="buttons">
            <Button
            className="add_button"
            // disabled={isDisabled}
            onClick={handleAddAnotherPurchase}
          >
            {t(`practical.add_new`)}
          </Button>
          </div>
        <div className="sales_info_modal">
          <div className="info between">
            {/* <img src="/Image/faker_user.png" alt="" /> */}
            <span className="mr"
            style={{marginRight:"20px"}}>
              <h5>
                {student_info?.first_name + " " + student_info?.last_name}
              </h5>
              <h5>
                {t("models.course")}: <p> {student_info?.grade_name}</p>
              </h5>
            </span>
                        <span className="ml-20" 
            style={{marginLeft:"20px"}}
            >
              <h5>
                {t("models.mobile_number")}: <p> {student_info?.phone_number}</p>
              </h5>
            </span>
          </div>
          <ValidationField
            placeholder="choose"
            label="package"
            name="package_id"
            type="Select"
            option={PackagesInfo}
            disabled
            allowClear={false}
            onKeyDown={handleKeyDown}
          />
        </div>


      <div className="buttons">
          <Button className="back_button pointer" onClick={handleCloseModel}>
            {t("practical.cancel")}
          </Button>
          <Button
            className="add_button"
            disabled={isDisabled}
            onClick={handleNext}
          >
            {t(`practical.yes`)}
            {isDisabled && (
              <span className="Spinier_Div">
                <Spin />
              </span>
            )}
          </Button>
        </div>

      </div>
    )
  );
};

export default Form;
