import Button from "antd/lib/button";
import Modal from "components/Modal";
import { Formik } from "formik";
import pick from "lodash/pick";
import { BandsintownItem } from "models/talent/talent-profile-module.model";
import React, { useEffect, useState } from "react";
import * as yup from "yup";
import { bandsintownService } from "../../services";
import notification from "../../utils/notification";
import { bandsintownParseUri } from "../../utils/url";
import "./BandsintownEditorModal.scss";
import LinkEditorForm from "./components/Form/Form";
import "../LinkEditorModal/LinkEditorModal.scss";

export type BandsintownEditorModalFormValues = Pick<
  BandsintownItem,
  "url" | "visible"
>;

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

const initialProductValues: BandsintownItem = {
  url: "",
  visible: true,
};

const validateSchema = yup.object().shape({
  // Validate form field
  url: yup
    .string()
    .required("This field must be a valid URL.")
    .url("This field must be a valid URL.")
    .matches(
      /((https?):\/\/)?(www.)?bandsintown.(com)\/.*/,
      "Please enter a valid Bandsintown profile URL"
    ),
});

const BandsintownEditorModal: React.FC<BandsintownEditorModalProps> = ({
  visible,
  isEdit,
  item,
  onChangeVisible,
  onConfirmCallback,
}) => {
  const [initialValues, setInitialValues] = useState<BandsintownItem>({
    visible: true,
  });

  useEffect(() => {
    if (!visible) return;
    if (isEdit && item) {
      setInitialValues({
        ...pick(item, ["id", "url", "visible"]),
      } as BandsintownItem);
    } else {
      setInitialValues(initialProductValues);
    }
  }, [visible, isEdit, item]);

  const handleSubmit = async (values: any) => {
    try {
      const info = bandsintownParseUri(values.url);
      if (!info) {
        notification.error({
          message: "Please enter the correct Bandsintown link",
        });
        return;
      }
      if (info.type !== "artist") {
        notification.error({
          message: "Please enter the correct Bandsintown artist profile link",
        });
        return;
      }
      const result: any = await bandsintownService.getArtistById(
        info.id as number
      );

      if (!result.ok || !result.response) {
        notification.error({
          message: "The artist not found, please check link again",
        });
        return;
      }
      onConfirmCallback({
        ...values,
        metadata: {
          name: result.response.name,
          id: result.response.id,
        },
      });
    } catch (error) {}
  };

  return (
    <React.Fragment>
      <Modal
        width={664}
        closable
        centered
        className="link-editor-modal"
        title={
          isEdit ? "Edit Bandsintown Module" : "Add New Bandsintown 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()}
                  >
                    {isEdit ? "Save" : "Done"}
                  </Button>
                </div>
              </React.Fragment>
            )}
          </Formik>
        </div>
      </Modal>
    </React.Fragment>
  );
};

export default BandsintownEditorModal;
