import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";
import { useFormik } from "formik";
import {
  CreateOfferFormContainer,
  DescriptionField,
  FieldLabel,
  NextButton,
  SelectOption,
  TitleField,
} from "./FirstPartCreateOffer.styled";
import * as Yup from "yup";
import selectedTheme from "../../../../themes";
import { useTranslation } from "react-i18next";
import { SelectField } from "../CreateOffer.styled";
import { useSelector } from "react-redux";
import useScreenDimensions from "../../../../hooks/useScreenDimensions";

const FirstPartCreateOffer = (props) => {
  const [subcat, setSubcat] = useState([]);
  const locations = useSelector((state) => state.locations.locations);
  const categories = useSelector((state) => state.categories.categories);
  const dimensions = useScreenDimensions();

  const { t } = useTranslation();

  useEffect(() => {
    if (!props.offer) {
      if (Object.keys(props.informations).length !== 0) {
        formik.setFieldValue("nameOfProduct", props.informations.nameOfProduct);
        formik.setFieldValue("description", props.informations.description);
        formik.setFieldValue("location", props.informations.location);
        formik.setFieldValue("category", props.informations.category);
        formik.setFieldValue("subcategory", props.informations.subcategory);
        let scat = categories.filter(
          (cat) => cat.name === props.informations.category
        );
        setSubcat(scat[0].subcategories.map((x) => x.name));
      }
    } else {
      formik.setFieldValue("location", props.offer.location.city);
      formik.setFieldValue("category", props.offer.category.name);
      formik.setFieldValue("subcategory", props.offer.subcategory);
    }
  }, [props.offer, props.informations]);

  useEffect(() => {
    if (props.offer !== undefined) {
      let scat = categories.filter(
        (cat) => cat.name === props.offer.category.name
      );
      setSubcat(scat[0].subcategories.map((x) => x.name));
    }
  }, [props.offer]);

  const handleSubmit = (values) => {
    props.handleNext(values);
  };
  const formik = useFormik({
    initialValues: {
      nameOfProduct: `${!props.offer ? "" : props.offer.name}`,
      description: `${!props.offer ? "" : props.offer.description}`,
      location: "default",
      category: "default",
      subcategory: "default",
    },
    validationSchema: Yup.object().shape({
      nameOfProduct: Yup.string().required(t("login.nameOfProductRequired")),
      description: Yup.string().required(t("login.descriptionRequired")).min(8),
      location: Yup.string().oneOf(locations.map((l) => l.city)),
      category: Yup.string().oneOf(categories.map((c) => c.name)),
      // subcategory: Yup.string().oneOf(
      //   subcat[0]?.subcategories ? subcat[0].subcategories : []
      // ),
    }),
    onSubmit: handleSubmit,
    validateOnBlur: true,
    enableReinitialize: true,
  });

  const handleSubcategories = (category) => {
    const filtered = categories.filter((cat) => cat.name === category);
    setSubcat(filtered[0].subcategories.map((c) => c.name));
  };

  return (
    <>
      <CreateOfferFormContainer component="form" onSubmit={formik.handleSubmit}>
        <FieldLabel leftText={t("offer.title")} />
        <TitleField
          name="nameOfProduct"
          placeholder={t("offer.productName")}
          italicPlaceholder
          margin="normal"
          value={formik.values.nameOfProduct}
          onChange={formik.handleChange}
          error={formik.touched.nameOfProduct && formik.errors.nameOfProduct}
          helperText={
            formik.touched.nameOfProduct && formik.errors.nameOfProduct
          }
          autoFocus
          fullWidth
        />

        <FieldLabel leftText={t("offer.productDescription")} />
        {dimensions.width > 600 ? (
          <DescriptionField
            name="description"
            placeholder={t("offer.description")}
            margin="normal"
            italicPlaceholder
            value={formik.values.description}
            onChange={formik.handleChange}
            error={formik.touched.description && formik.errors.description}
            helperText={formik.touched.description && formik.errors.description}
            fullWidth
            multiline
            minRows={4}
            height={"100px"}
          />
        ) : (
          <DescriptionField
            name="description"
            placeholder={t("offer.description")}
            margin="normal"
            italicPlaceholder
            value={formik.values.description}
            onChange={formik.handleChange}
            error={formik.touched.description && formik.errors.description}
            helperText={formik.touched.description && formik.errors.description}
            fullWidth
          />
        )}

        <FieldLabel leftText={t("offer.location")} />
        <SelectField
          defaultValue={formik.values.location}
          onChange={(value) => {
            formik.setFieldValue("location", value.target.value);
          }}
          value={formik.values.location}
        >
          <SelectOption style={{ display: "none" }} value="default">
            {t("offer.choseLocation")}
          </SelectOption>
          {locations.map((loc) => {
            return (
              <SelectOption key={loc._id} value={loc.city}>
                {loc.city}
              </SelectOption>
            );
          })}
        </SelectField>

        <FieldLabel leftText={t("offer.category")} />
        <SelectField
          defaultValue={formik.values.category}
          onChange={(value) => {
            formik.setFieldValue("category", value.target.value);
          }}
          value={formik.values.category}
        >
          <SelectOption style={{ display: "none" }} value="default">
            {t("offer.choseCategory")}
          </SelectOption>
          {categories.map((cat, i) => {
            return (
              <SelectOption
                key={i}
                value={cat.name}
                onClick={() => handleSubcategories(cat.name)}
              >
                {cat.name}
              </SelectOption>
            );
          })}
        </SelectField>

        <FieldLabel leftText={t("offer.subcategory")} />
        <SelectField
          defaultValue={formik.values.subcategory}
          onChange={(value) => {
            formik.setFieldValue("subcategory", value.target.value);
          }}
          value={formik.values.subcategory}
        >
          <SelectOption style={{ display: "none" }} value="default">
            {t("offer.choseSubcategory")}
          </SelectOption>
          {subcat &&
            subcat.map((sub, i) => {
              return (
                <SelectOption key={i} value={sub}>
                  {sub}
                </SelectOption>
              );
            })}
        </SelectField>
      </CreateOfferFormContainer>

      <NextButton
        type="submit"
        variant="contained"
        height="48px"
        fullWidth
        buttoncolor={selectedTheme.primaryPurple}
        textcolor="white"
        onClick={formik.handleSubmit}
        disabled={
          formik.values?.nameOfProduct?.length === 0 ||
          !formik.values?.nameOfProduct ||
          formik.values?.description?.length === 0 ||
          !formik.values?.description ||
          formik.values?.category?.length === 0 ||
          !formik.values?.category ||
          formik.values?.category === "default" ||
          formik.values?.subcategory?.length === 0 ||
          !formik.values?.subcategory ||
          formik.values?.subcategory === "default" ||
          formik.values?.location?.length === 0 ||
          !formik.values?.location ||
          formik.values?.location === "default"
        }
      >
        {t("offer.continue")}
      </NextButton>
    </>
  );
};

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

export default FirstPartCreateOffer;
