import React, { useMemo, useState, useEffect } from "react";
import PropTypes from "prop-types";
import {
  CreateOfferFormContainer,
  FieldLabel,
  Scroller,
  SupportedFormats,
  InputButtonContainer,
} from "./SecondPartCreateOffer.styled";
import ImagePicker from "../../../ImagePicker/ImagePicker";
import { useTranslation, Trans } from "react-i18next";
import { SelectAltText, SelectField, SelectText } from "../CreateOffer.styled";
import {
  NextButton,
  SelectOption,
} from "../FirstPart/FirstPartCreateOffer.styled";
import selectedTheme from "../../../../themes";
import { conditionSelectEnum } from "../../../../enums/conditionEnum";
import { useFormik } from "formik";
import * as Yup from "yup";

const numberOfImages = 3;

const SecondPartCreateOffer = (props) => {
  const [images, setImages] = useState(
    Array.apply(null, Array(numberOfImages)).map(() => {})
  ); // 3 images
  const { t } = useTranslation();

  useEffect(() => {
    if (!props.offer) {
      if (Object.keys(props.informations).length > 6) {
        setImages(
          props.informations?.images
            ? [...props.informations.images]
            : [...images]
        );
        formik.setFieldValue(
          "condition",
          props.informations?.condition
            ? props.informations.condition
            : "default"
        );
      }
    } else {
      formik.setFieldValue("condition", props.offer.condition);
    }
  }, [props.offer, props.informations]);

  useEffect(() => {
    setImages((prevState) => {
      let editedImages = [...prevState];
      if (props.offer !== undefined && props.offer.images.length === 1) {
        editedImages[0] = props.offer.images[0];
      }

      if (props.offer !== undefined && props.offer.images.length === 2) {
        editedImages[0] = props.offer.images[0];
        editedImages[1] = props.offer.images[1];
      }

      return [...editedImages];
    });
  }, [props.offer]);

  const setImage = (index, image) => {
    setImages((prevState) => {
      let newState = [...prevState];
      newState[index] = image;
      return [...newState];
    });
  };

  const imagesEmpty = useMemo(() => {
    let numOfImagesEmpty = 0;
    images.forEach((item) => {
      if (item === null || item === undefined) numOfImagesEmpty++;
    });
    return numOfImagesEmpty;
  }, [images]);

  const handleSubmit = (values) => {
    props.handleNext(values);
  };

  const conditionSelectEnumArray = Object.values(conditionSelectEnum);
  const filteredconditionSelectEnumArray = conditionSelectEnumArray.map(
    (item) => item.mainText
  );

  const formik = useFormik({
    initialValues: {
      images: images,
      condition:
        props.informations?.condition || props.offer?.condition || "default",
    },
    validationSchema: Yup.object().shape({
      condition: Yup.string()
        .required()
        .oneOf(filteredconditionSelectEnumArray),
    }),
    onSubmit: handleSubmit,
    validateOnBlur: true,
    enableReinitialize: true,
  });

  return (
    <>
      <CreateOfferFormContainer component="form" onSubmit={formik.handleSubmit}>
        <Scroller>
          {images.map((item, index) => {
            return (
              <ImagePicker
                key={index}
                image={item}
                setImage={(image) => setImage(index, image)}
                deleteImage={() => setImage(index, null)}
                showDeleteIcon
              />
            );
          })}
        </Scroller>
        <SupportedFormats>
          <Trans i18nKey="offer.supportedImagesFormats" />
        </SupportedFormats>
        <InputButtonContainer>
          <FieldLabel leftText={t("offer.condition")} />
          <SelectField
            onChange={(value) => {
              formik.setFieldValue("condition", value.target.value);
            }}
            value={formik.values.condition}
          >
            <SelectOption style={{ display: "none" }} value="default">
              {t("offer.choseCondition")}
            </SelectOption>
            {Object.keys(conditionSelectEnum).map((key) => {
              var item = conditionSelectEnum[key];
              return (
                <SelectOption value={item.mainText} key={item.value}>
                  <SelectText>{item.mainText}</SelectText>
                  <SelectAltText>{item.altText}</SelectAltText>
                </SelectOption>
              );
            })}
          </SelectField>
        </InputButtonContainer>
      </CreateOfferFormContainer>
      <NextButton
        type="submit"
        variant="contained"
        height="48px"
        fullWidth
        buttoncolor={selectedTheme.primaryPurple}
        textcolor="white"
        onClick={formik.handleSubmit}
        disabled={
          (props.offer === undefined
            ? imagesEmpty === numberOfImages
            : false) ||
          formik.values?.condition?.length === 0 ||
          !formik.values?.condition ||
          formik.values?.condition === "default"
        }
      >
        {t("offer.continue")}
      </NextButton>
    </>
  );
};

SecondPartCreateOffer.propTypes = {
  children: PropTypes.node,
  handleNext: PropTypes.func,
  offer: PropTypes.node,
  informations: PropTypes.any,
};

export default SecondPartCreateOffer;
