import Modal from "components/Modal";
import React, { useCallback } from "react";
import { SHOPIFY_STORE_DOMAIN } from "constants/regexp";
import { isMobile } from "react-device-detect";
import Tooltip from "antd/lib/tooltip";
import { Text } from "components/Typography";
import { Icon } from "components/Icon";
import { Button, Form, Input, Row } from "antd";
import { useForm } from "antd/lib/form/Form";
import { shopifyService } from "services";
import notification from "utils/notification";
import { useTypedSelector } from "redux/rootReducer";
import PopupWindow from "components/PopupWindowShopifyAuth";
import { selectShopifyStores } from "redux/Shopify/selector";
import { setShopifyStoreAction } from "redux/Shopify/actions";
import { useDispatch } from "react-redux";
import "./index.scss";

interface ConnectShopifyModalProps {
  toggleModal: (value: boolean) => void;
  callback?: () => void;
}

const ShopifyStoreDomainInputModal = ({
  toggleModal,
  callback,
}: ConnectShopifyModalProps) => {
  const dispatch = useDispatch();
  const [form] = useForm();

  const stores = useTypedSelector(selectShopifyStores);

  const handleOpenLoginPage = async () => {
    const storeDomain = form.getFieldValue("storeDomain");
    if (
      stores.length &&
      !!stores.find((store) => store.domain === storeDomain)
    ) {
      notification.error({
        message: "This store is already added",
      });
      toggleModal(false);
      return;
    }
    const respData: any = await shopifyService.getAuthUrl(storeDomain);
    if (respData.ok) {
      const popup = PopupWindow.open(
        "shopify-authorization",
        respData.data.authUrl,
        {
          height: 600,
          width: 1000,
        }
      );

      popup.then(
        (data: any) => {
          if (
            data.cancelled_app_install ||
            data.scope === "unauthenticated_read_product_listings"
          ) {
            notification.error({
              message:
                "Your Shopify connection was unsuccessful. Please try connecting again to start adding products from your Shopify store.",
            });
          } else {
            dispatch(
              setShopifyStoreAction([
                ...stores,
                {
                  name: data.shop,
                  accessToken: data.accessToken,
                  domain: data.shop,
                  order: data.order,
                  connected: true,
                },
              ])
            );
            callback && callback();
          }
        },
        (error: any) => {
          notification.error({
            message:
              "Your Shopify connection was unsuccessful. Please try connecting again to start adding products from your Shopify store.",
          });
        }
      );
    }
    toggleModal(false);
  };

  const handleSubmit = useCallback(() => {
    form.validateFields().then(() => {
      handleOpenLoginPage();
    });
  }, [form]);

  return (
    <Modal
      closable
      centered
      className="store-domain-input-modal"
      visible
      title="Connect Shopify"
      onCancel={() => toggleModal(false)}
      width={664}
    >
      <Row align="middle" className="m__b--16">
        <Text preset="semibold18">What is your Shopify URL?</Text>
        <Tooltip
          className="align__self--center"
          overlayClassName="store-domain-input-modal__tooltip"
          placement={isMobile ? "bottom" : "bottomLeft"}
          title="Your Shopify store URL will be in the format  [your-shop-name].myshopify.com. 
          If you can’t remember your shop URL you can find it by logging into your Shopify admin."
          color={"#000"}
        >
          <div className="height--24 width--24 m__l--8">
            <Icon name="question" />
          </div>
        </Tooltip>
      </Row>
      <Row className="m__b--8">
        <Text preset="regular14">Store domain</Text>
      </Row>
      <Form
        onFieldsChange={(fields) => {
          const url = fields[0].value
            ?.replace(/(^\w+:|^)\/\//, "")
            .replace("/", "");
          form.setFieldsValue({ storeDomain: url });
        }}
        form={form}
        onFinish={handleSubmit}
      >
        <Form.Item
          rules={[
            {
              required: true,
              message: "Please enter this field",
            },
            {
              pattern: SHOPIFY_STORE_DOMAIN,
              message: "Please enter a valid Shopify store link",
            },
          ]}
          name="storeDomain"
        >
          <Input autoFocus placeholder="store.myshopify.com" />
        </Form.Item>
        <Form.Item className="m__b--16">
          <Button
            className="text__transform--uppercase letter__spacing--1"
            type="primary"
            size="large"
            htmlType="submit"
            block
          >
            Continue to Log In
          </Button>
        </Form.Item>
      </Form>

      <Row className="m__t--16">
        <Text preset="regular14">
          A Shopify login window will appear and you’ll be prompted to enter the
          username and password for your store. Once you are logged in, you’ll
          be redirected back to Komi.
        </Text>
      </Row>
    </Modal>
  );
};

export default ShopifyStoreDomainInputModal;
