import Button from "antd/lib/button";
import Modal from "components/Modal";
import { Formik } from "formik";
import React from "react";
import * as yup from "yup";
import LinkEditorForm from "./components/Form/Form";
import "../LinkEditorModal/LinkEditorModal.scss";

export type ThroneLinkModalFormValues = {
  url: string;
};

interface ThroneLinkModalProps {
  visible: boolean;
  onChangeVisible: (value: boolean) => void;
  onConfirmCallback: (url: string) => void;
}

const initialValues: ThroneLinkModalFormValues = {
  url: "https://throne.com/",
};

const validateSchema = yup.object().shape({
  // Validate form field
  url: yup
    .string()
    .required("Please enter a valid Throne wishlist URL")
    .url("Please enter a valid Throne wishlist URL")
    .matches(
      /(https:\/\/)?(www.)?throne.(com)\/.+/,
      "Please enter a valid Throne wishlist URL"
    ),
});

const ThroneLinkModal: React.FC<ThroneLinkModalProps> = ({
  visible,
  onChangeVisible,
  onConfirmCallback,
}) => {
  const handleSubmit = async (values: ThroneLinkModalFormValues) => {
    onConfirmCallback(values.url);
  };

  return (
    <React.Fragment>
      <Modal
        width={664}
        closable
        centered
        className="link-editor-modal"
        title="Add New Throne Module"
        visible={visible}
        onCancel={() => onChangeVisible(false)}
        destroyOnClose
        maskClosable={false}
      >
        <div>
          <Formik
            initialValues={initialValues}
            onSubmit={handleSubmit}
            validationSchema={validateSchema}
          >
            {(props) => (
              <React.Fragment>
                <LinkEditorForm {...props} />
                <div className="link-editor__actions m__t--16">
                  <Button
                    className="ant-btn-xl ant-btn-uppercase"
                    onClick={() => onChangeVisible(false)}
                  >
                    Cancel
                  </Button>
                  <Button
                    className="ant-btn-xl ant-btn-uppercase"
                    type="primary"
                    onClick={() => props.handleSubmit()}
                  >
                    Done
                  </Button>
                </div>
              </React.Fragment>
            )}
          </Formik>
        </div>
      </Modal>
    </React.Fragment>
  );
};

export default ThroneLinkModal;
