import { Row } from "antd";
import Button from "antd/lib/button";
import Modal from "components/Modal";
import { URL_REG } from "constants/regexp";
import { Formik } from "formik";
import pick from "lodash/pick";

import { ProductItem } from "models/talent/talent-profile-module.model";
import React, { useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { MediaUpload } from "redux/Common/types";
import {
  selectExchangeRates,
  selectLocalizationSelected,
} from "redux/User/selector";
import notification from "utils/notification";
import * as yup from "yup";
import { CurrencyCodes } from "../../constants/currency-code";
import { Paragraph } from "../Typography";
import CoverUpload from "./components/CoverUpload/CoverUpload";
import ProductEditorForm from "./components/Form/Form";
import { useTypedSelector } from "redux/rootReducer";
import "./ProductEditorModal.scss";

export type ProductEditorModalFormValues = Pick<
  ProductItem,
  "thumbnail" | "url" | "title" | "price" | "currency" | "visible"
>;

interface ProductEditorModalProps {
  show: boolean;
  isEdit: boolean;
  product?: ProductItem;
  toggleModal: (value: boolean) => void;
  onConfirmCallback: (product: ProductItem) => void;
}

const initialProductValues: ProductItem = {
  title: "",
  url: "",
  price: undefined,
  visible: true,
};

const validateSchema = yup.object().shape({
  // Validate form field
  title: yup.string().required("Enter your product name"),
  url: yup
    .string()
    .matches(URL_REG, "Wrong Format URL")
    .required("Please fill the product link"),
  price: yup
    .number()
    .typeError("Please enter the product price")
    .min(0, "Please enter the product price")
    .required("Please enter the product price"),
});

const ProductEditorModal: React.FC<ProductEditorModalProps> = ({
  show,
  isEdit,
  product,
  toggleModal,
  onConfirmCallback,
}) => {
  const [photo, setPhoto] = useState<MediaUpload>({});
  const [initialValues, setInitialValues] =
    useState<ProductItem>(initialProductValues);
  const [currency, setCurrency] = useState("");
  const localizationSelected = useTypedSelector(selectLocalizationSelected);
  const [loadingButton, setLoadingButton] = useState(false);

  const localizationCurrency = useMemo(
    () => CurrencyCodes?.[localizationSelected?.currency || "USD"],
    [localizationSelected]
  );
  const currencyData = useMemo(() => {
    return currency?.split(" ");
  }, [currency]);

  useEffect(() => {
    if (!show || !localizationCurrency) return;
    if (isEdit && product) {
      setInitialValues({
        ...pick(product, ["id", "url", "title", "price", "order"]),
        visible: product.visible,
      });
      setPhoto({
        url: product.thumbnail,
      });
      const item = CurrencyCodes[product.currency?.toUpperCase() || "USD"];
      setCurrency(`${item.symbol} ${product.currency?.toUpperCase() || "USD"}`);
    } else {
      setInitialValues(initialProductValues);
      setPhoto({});
      setCurrency(
        `${localizationCurrency?.symbol} ${localizationCurrency?.code}`
      );
    }
  }, [show, isEdit, product, localizationCurrency]);

  const uploadPhotoSuccess = (file: MediaUpload) => {
    setPhoto(file);
  };

  const removePhoto = () => {
    setPhoto({});
  };

  const handleSubmit = (formProps: ProductEditorModalFormValues) => {
    setLoadingButton(true);
    if (!photo.url) {
      notification.warn({ message: "Please add the Cover Photo" });
      setLoadingButton(false);
      return;
    }
    const currencyData = currency.split(" ");
    onConfirmCallback({
      ...formProps,
      price: Number(formProps.price),
      thumbnail: photo.url as string,
      currency: currencyData[1],
    });
    setLoadingButton(false);
  };

  return (
    <React.Fragment>
      <Modal
        width={664}
        closable
        centered
        className="product-editor-modal"
        title={isEdit ? "Edit Product" : "Add New Product"}
        visible={show}
        onCancel={() => toggleModal(false)}
        destroyOnClose
        maskClosable={false}
      >
        <div>
          <div className="m__b--32">
            <CoverUpload
              photo={photo}
              onUploadSuccess={uploadPhotoSuccess}
              onRemove={removePhoto}
            />
          </div>
          <Formik
            initialValues={initialValues}
            onSubmit={handleSubmit}
            validationSchema={validateSchema}
          >
            {(props) => (
              <React.Fragment>
                <ProductEditorForm
                  {...props}
                  currency={currency}
                  setCurrency={setCurrency}
                />
                {currencyData?.[1] !== localizationCurrency?.code ? (
                  <Row
                    align="middle"
                    className="p__x--16 p__y--8 bg--grey border__radius--8"
                  >
                    <Paragraph className="leading-22">
                      Please note that your account currency will not be
                      affected when you manually set currency for individual
                      products.
                    </Paragraph>
                  </Row>
                ) : null}
                <div className="product-editor__actions m__t--24">
                  <Button
                    className="ant-btn-xl ant-btn-uppercase"
                    onClick={() => toggleModal(false)}
                  >
                    Cancel
                  </Button>
                  <Button
                    className="ant-btn-xl ant-btn-uppercase"
                    type="primary"
                    onClick={() => props.handleSubmit()}
                    disabled={loadingButton}
                  >
                    {isEdit ? "Save" : "Done"}
                  </Button>
                </div>
              </React.Fragment>
            )}
          </Formik>
        </div>
      </Modal>
    </React.Fragment>
  );
};

export default ProductEditorModal;
