import Button from "antd/lib/button";
import Modal from "components/Modal";
import { Formik } from "formik";
import pick from "lodash/pick";
import { SeatedItem } from "models/talent/talent-profile-module.model";
import React, { useEffect, useState } from "react";
import * as yup from "yup";
import { seatedService } from "../../services";
import "./SeatedEditorModal.scss";
import LinkEditorForm from "./components/Form/Form";
import { Alert, Row, Spin } from "antd";
import { Icon } from "components/Icon";
import DotLoading from "components/DotLoading";
import "../LinkEditorModal/LinkEditorModal.scss";

export type SeatedEditorModalFormValues = Pick<
  SeatedItem,
  "seatedId" | "visible"
>;

interface SeatedEditorModalProps {
  visible: boolean;
  isEdit: boolean;
  item?: SeatedItem;
  onChangeVisible: (value: boolean) => void;
  onConfirmCallback: (link: SeatedItem) => void;
}

const initialProductValues: SeatedItem = {
  seatedId: "",
  visible: true,
};

const validateSchema = yup.object().shape({
  seatedId: yup
    .string()
    .required("Please enter a valid Seated Artist ID")
    .test("len", "Please enter a valid Seated Artist ID", (val) => {
      const regex =
        /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
      return regex.test(String(val).trim());
    }),
});

const SeatedEditorModal: React.FC<SeatedEditorModalProps> = ({
  visible,
  isEdit,
  item,
  onChangeVisible,
  onConfirmCallback,
}) => {
  const [initialValues, setInitialValues] =
    useState<SeatedItem>(initialProductValues);
  const [artistIDError, setArtistIDError] = useState(false);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    if (!visible) return;
    if (isEdit && item) {
      setInitialValues({
        ...pick(item, "seatedId", "visible"),
      });
    } else {
      setInitialValues(initialProductValues);
    }
    setArtistIDError(false);
  }, [visible, isEdit, item]);

  const handleSubmit = async (values: any) => {
    try {
      //Trim whitespaces
      values.seatedId = String(values.seatedId).trim();
      setLoading(true);
      const result: any = await seatedService.getValidateSeated(
        values.seatedId as number
      );
      if (
        !result.ok ||
        !result.response ||
        (result.ok && result.response.status !== 200)
      ) {
        setArtistIDError(true);
        setLoading(false);
        return;
      }
      if (result.ok && result.response.status === 200) {
        onConfirmCallback({
          seatedId: values.seatedId,
          visible: values.visible,
        });
      }
      setLoading(false);
      setArtistIDError(false);
      onChangeVisible(false);
    } catch (error) {}
  };
  return (
    <React.Fragment>
      <Modal
        width={664}
        closable
        centered
        className="link-editor-modal"
        title={isEdit ? "Edit Seated Module" : "Add New Seated Module"}
        visible={visible}
        onCancel={() => onChangeVisible(false)}
        destroyOnClose
        maskClosable={false}
      >
        <Spin
          spinning={loading}
          indicator={
            <Row align="middle" justify="center">
              <DotLoading />
            </Row>
          }
        >
          <div>
            <Formik
              initialValues={initialValues}
              onSubmit={handleSubmit}
              validationSchema={validateSchema}
            >
              {(props) => (
                <React.Fragment>
                  <LinkEditorForm {...props} />
                  {artistIDError && (
                    <div className={"validate-connection"}>
                      <Alert
                        message={undefined}
                        className={
                          "m__b--24 p__x--8 p__y--8 bg--darkGray border--none"
                        }
                        style={{ marginTop: "-8px" }}
                        type="error"
                        description={
                          <div>
                            Connection with Seated could not be established at
                            this time. Please make sure that your Artist ID is
                            correct. If so, try adding it again later.
                          </div>
                        }
                        icon={<Icon name="error" />}
                        showIcon
                        closable
                      />
                    </div>
                  )}

                  <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()}
                    >
                      {isEdit ? "Save" : "Done"}
                    </Button>
                  </div>
                </React.Fragment>
              )}
            </Formik>
          </div>
        </Spin>
      </Modal>
    </React.Fragment>
  );
};

export default SeatedEditorModal;
