import { Col, Row } from "reactstrap";
import ValidationField from "../../../../Components/ValidationField/ValidationField";
import { useFormikContext } from "formik";
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 { useEffect, useState } from "react";
import { useGetStudentByPhone } from "../../../../api/sales";
import { ModalBodyProps } from "../../../../types/Sales";

const Form = ({
  handleCloseModel = () => {},
}:ModalBodyProps) => {
  
  const [ triggerApi, setTriggerApi] = useState(false)
  const { setObjectToEdit } = useObjectToEdit();
  const {t} = useTranslation();
  

  const formik = useFormikContext();
  const {values,setFieldValue} = useFormikContext<any>()
  const  phoneNumber : number =  values?.phone_number 

  const { data, status, isSuccess } = useGetStudentByPhone({
    phone_number:phoneNumber,
  },{
    enabled: triggerApi
  });

  const handleNext = ()=>{
    if(values?.phone_number && phoneNumber.toString().length === 10 ){
      setTriggerApi(true);
      setObjectToEdit({data})
    }
  }


  useEffect(() => {
    if(isSuccess){
      setTriggerApi(false);
      setObjectToEdit({data})
      setFieldValue( "currentModalIndex" , values?.currentModalIndex + 1 )
    }
  }, [isSuccess]);


  return (
    values?.currentModalIndex == 0 &&      
    <div className="w-100">

      <header className="modal_title">
        <span>
          {t(`models.add_sales`)}{" "}
        </span>
        <MdCancel onClick={handleCloseModel} />
      </header>

      <Divider />

      <Row className="w-100">
        <Col>
          <ValidationField
            placeholder="phone_number"
            label="phone_number"
            name="phone_number"
          />
          <Divider className="margin_auto"/>
        </Col>

        <div className="buttons">
          <Button className="back_button pointer" onClick={handleCloseModel}>
            {t("practical.cancel")}
          </Button>
          <Button
            className="add_button"
            disabled={status === QueryStatusEnum.LOADING || !formik.dirty || !values?.phone_number}
            onClick={handleNext}
          >
            {t(`practical.sale`)}
            {status === QueryStatusEnum.LOADING && (
              <span className="Spinier_Div">
                <Spin />
              </span>
            )}
          </Button>
        </div>

      </Row>
      
    </div>
  );
};

export default Form;
