import React, { useState } from "react";
import PropTypes from "prop-types";
import { useDispatch, useSelector } from "react-redux";
import {
  CreateOfferContainer,
  CreateOfferTitle,
  ModalCreateOfferContainer,
  ModalHeader,
} from "./CreateOffer.styled";
import StepProgress from "../../StepProgress/StepProgress";
import FirstPartCreateOffer from "./FirstPart/FirstPartCreateOffer";
import SecondPartCreateOffer from "./SecondPart/SecondPartCreateOffer";
import ThirdPartCreateOffer from "./ThirdPart/ThirdPartCreateOffer";
import {
  addOffer,
  fetchOffers,
  fetchOneOffer,
  fetchProfileOffers,
} from "../../../store/actions/offers/offersActions";
import { selectUserId } from "../../../store/selectors/loginSelectors";
import { editOneOffer } from "../../../store/actions/offers/offersActions";
import { useTranslation } from "react-i18next";
import BackdropComponent from "../../MUI/BackdropComponent";
import CloseButton from "./CloseButton/CloseButton";
import BackButton from "./BackButton/BackButton";

const CreateOffer = ({ closeCreateOfferModal, editOffer, offer }) => {
  const dispatch = useDispatch();
  const [informations, setInformations] = useState({});
  const [currentStep, setCurrentStep] = useState(1);
  const { t } = useTranslation();
  const userId = useSelector(selectUserId);

  const handleApiResponseSuccess = () => {
    if (editOffer) {
      dispatch(fetchOneOffer(offer._id));
      dispatch(fetchProfileOffers(userId));
    } else {
      dispatch(fetchOffers({ queryString: "" }));
      dispatch(fetchProfileOffers(userId));
      dispatch(fetchOneOffer(offer._id));
    }
  };

  const handleNext = (values) => {
    setInformations({ ...informations, ...values });
    setCurrentStep((prevState) => prevState + 1);
  };

  const newImgs =
    informations.images &&
    informations.images
      .filter((img) => img !== undefined)
      .map((img) =>
        img
          .replace("data:image/jpg;base64,", "")
          .replace("data:image/jpeg;base64,", "")
          .replace("data:image/png;base64,", "")
      );

  const offerData = {
    name: informations.nameOfProduct,
    description: informations.description,
    location: {
      city: informations.location,
    },
    condition: informations.condition,
    category: {
      name: informations.category,
    },
    subcategory: informations.subcategory,
    images: newImgs,
  };

  const submitOffer = (values) => {
    dispatch(addOffer({ values, handleApiResponseSuccess }));
  };

  const submitEditOffer = (id, values) => {
    dispatch(editOneOffer(id, values));
  };

  const handleSubmitOffer = () => {
    if (editOffer === undefined) {
      submitOffer({ offerData, handleApiResponseSuccess });
    } else {
      const offerId = offer._id;
      submitEditOffer({ offerId, offerData, handleApiResponseSuccess });
    }
    closeCreateOfferModal(false);
  };

  const goStepBack = (stepNumber) => {
    setCurrentStep(stepNumber);
    const {
      category,
      condition,
      description,
      images,
      location,
      nameOfProduct,
      subcategory,
    } = informations;
    if (stepNumber === 1) {
      setInformations({
        category,
        condition,
        description,
        location,
        nameOfProduct,
        subcategory,
      });
    }
    if (stepNumber === 2) {
      setInformations({
        category,
        condition,
        description,
        images,
        location,
        nameOfProduct,
        subcategory,
      });
    }
  };

  return (
    <>
      <BackdropComponent
        isLoading
        handleClose={closeCreateOfferModal}
        position="fixed"
      />
      <ModalCreateOfferContainer currentStep={currentStep}>
        <CreateOfferContainer currentStep={currentStep}>
          <ModalHeader>
            <BackButton
              currentStep={currentStep}
              setCurrentStep={setCurrentStep}
            />
            <CreateOfferTitle component="h1" variant="h5">
              {currentStep === 3
                ? `${t("offer.review")}`
                : `${
                    editOffer !== undefined
                      ? `${t("offer.changeOffer")}`
                      : `${t("offer.newOffer")}`
                  }`}
            </CreateOfferTitle>
            <CloseButton closeCreateOfferModal={closeCreateOfferModal} />
          </ModalHeader>

          <StepProgress
            current={currentStep}
            numberOfSteps={3}
            functions={[() => goStepBack(1), () => goStepBack(2)]}
          />
          {currentStep === 1 && (
            <FirstPartCreateOffer
              handleNext={handleNext}
              offer={offer}
              informations={informations}
            />
          )}
          {currentStep === 2 && (
            <SecondPartCreateOffer
              handleNext={handleNext}
              offer={offer}
              informations={informations}
            />
          )}
          {currentStep === 3 && (
            <ThirdPartCreateOffer
              handleSubmitOffer={handleSubmitOffer}
              informations={informations}
            />
          )}
        </CreateOfferContainer>
      </ModalCreateOfferContainer>
    </>
  );
};

CreateOffer.propTypes = {
  history: PropTypes.shape({
    replace: PropTypes.func,
    push: PropTypes.func,
    location: PropTypes.shape({
      pathname: PropTypes.string,
    }),
  }),
  closeCreateOfferModal: PropTypes.func,
  editOffer: PropTypes.bool,
  offer: PropTypes.object,
};
export default CreateOffer;
