import { Col, Row } from "antd";
import classNames from "classnames";
import { AntInput, FieldType } from "components/Form/FormItem";
import { AntInputPriceNumber } from "components/Form/FormItemPriceNumber";
import { ErrorMessage, Field, FieldArray, Form, FormikProps } from "formik";
import React, { useCallback, useEffect, useMemo } from "react";
import { isMobile } from "react-device-detect";
import { selectLocalizationSelected } from "redux/User/selector";
import { ExchangeRate } from "redux/User/types";
import { useTypedSelector } from "redux/rootReducer";
import { addingHttpsPrefix } from "utils/string";
import { MediaUpload } from "../../../../redux/Common/types";
import { Icon } from "../../../Icon";
import CoverUpload from "../../../ProductEditorModal/components/CoverUpload/CoverUpload";
import { Paragraph, Text } from "../../../Typography";
import { OnDemandVideoEditorModalFormValues } from "../../OnDemandEditorModal";
import { getCurrencySymbol } from "utils/currency";

interface FormProductsProps {
  actions?: JSX.Element;
  exchangeRate?: ExchangeRate;
}

const FormProducts: React.FC<
  FormikProps<OnDemandVideoEditorModalFormValues> & FormProductsProps
> = ({ handleSubmit, values, actions, setTouched, touched }) => {
  const localizationSelected = useTypedSelector(selectLocalizationSelected);

  const isEmpty = useMemo(
    () => !values.products?.length,
    [values.products?.length]
  );
  useEffect(() => {
    setTouched({ ...touched, productSectionTitle: false });
  }, []);
  const uploadPhotoSuccess = useCallback(
    (helper, index) => (file: MediaUpload) => {
      const value = helper.form.values.products[index];
      const newItem = { ...value, image: file.url };
      helper.replace(index, newItem);
    },
    []
  );
  const removePhoto = useCallback(
    (helper, index) => () => {
      const value = helper.form.values.products[index];
      const newItem = { ...value, image: "" };
      helper.replace(index, newItem);
    },
    []
  );
  const handleRemoveItem = useCallback(
    (helper, index) => () => {
      helper.remove(index);
    },
    []
  );
  const handleClickAdd = useCallback(
    (helper) => () => {
      helper.push({
        link: "",
        name: "",
        price: null,
        image: "",
      });
    },
    []
  );
  const renderTitleSection = useCallback(() => {
    return (
      <>
        {!isEmpty ? (
          <div className="p__b--8">
            <Field
              component={AntInput}
              name="productSectionTitle"
              type={FieldType.input}
              label="Title of the section"
              placeholder="What kind of products are these? e.g. recommended products"
            />
          </div>
        ) : null}
      </>
    );
  }, [isEmpty]);
  return (
    <React.Fragment>
      <Form onSubmit={handleSubmit} className="form-products">
        {renderTitleSection()}
        <FieldArray
          name="products"
          render={(arrayHelpers) => (
            <div>
              {values.products?.map((item, index) => (
                <div key={index}>
                  <div className="m__b--32">
                    <CoverUpload
                      photo={{ url: item.image }}
                      onUploadSuccess={uploadPhotoSuccess(arrayHelpers, index)}
                      onRemove={removePhoto(arrayHelpers, index)}
                    />
                    <Row align="middle" justify="center">
                      <Text
                        className="text__align--center field-error"
                        preset="semibold14"
                      >
                        <ErrorMessage name={`products.${index}.image`} />
                      </Text>
                    </Row>
                  </div>
                  <Field
                    component={AntInput}
                    name={`products.${index}.link`}
                    type={FieldType.input}
                    description="Product URL"
                    placeholder="https://"
                    beforeSetValue={addingHttpsPrefix}
                  />
                  <Field
                    component={AntInput}
                    name={`products.${index}.name`}
                    type={FieldType.input}
                    description="Title"
                    placeholder="Enter title of the link"
                  />
                  <div
                    className={classNames(
                      "position--relative",
                      isMobile ? "p__b--24" : "p__b--8"
                    )}
                  >
                    <Field
                      component={AntInputPriceNumber}
                      name={`products.${index}.price`}
                      type={FieldType.inputNumber}
                      description="Price"
                      placeholder="Enter amount"
                      defaultValue={item.price || undefined}
                      prefix={getCurrencySymbol(
                        localizationSelected?.currency || "USD"
                      )}
                    />
                    <Row
                      className="form-products__delete cursor-pointer"
                      align="middle"
                      justify="end"
                    >
                      <Col onClick={handleRemoveItem(arrayHelpers, index)}>
                        <Text className="text--red" preset="semibold16">
                          Remove this product
                        </Text>
                      </Col>
                    </Row>
                  </div>
                  {index !== (values.products?.length || 0) - 1 ? (
                    <div className="p__b--32 p__t--8">
                      <div className={"form-products-divider"} />
                    </div>
                  ) : null}
                </div>
              ))}
              <div className={isEmpty ? "form-products__action" : ""}>
                <Row className="cursor-pointer" gutter={8} align="middle">
                  <Col
                    onClick={handleClickAdd(arrayHelpers)}
                    className="height--32"
                  >
                    <Icon name="add-blue" />
                  </Col>
                  <Col onClick={handleClickAdd(arrayHelpers)}>
                    <Paragraph
                      className="text--blue m__b--0"
                      preset="semibold18"
                    >
                      {isEmpty
                        ? "Add a product (optional)"
                        : "Add another product"}
                    </Paragraph>
                  </Col>
                </Row>
              </div>
            </div>
          )}
        />
        {actions}
      </Form>
    </React.Fragment>
  );
};

export default React.memo(FormProducts);
