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

import { YoutubeVideoItem } from "models/talent/talent-profile-module.model";
import React, { useEffect, useState } from "react";
import * as yup from "yup";
import YoutubeVideoEditorForm from "./components/Form/Form";
import "./YoutubeVideoEditorModal.scss";
import YoutubeOembed from "services/api/youtube-metadata.api";
import notification from "utils/notification";

export type YoutubeVideoEditorModalFormValues = Pick<
  YoutubeVideoItem,
  "url" | "visible"
>;

interface YoutubeVideoEditorModalProps {
  show: boolean;
  isEdit: boolean;
  item?: YoutubeVideoItem;
  toggleModal: (value: boolean) => void;
  onConfirmCallback: (item: YoutubeVideoItem) => void;
}

const initialYoutubeVideoValues: YoutubeVideoItem = {
  url: "",
  visible: true,
};

const validateSchema = yup.object().shape({
  url: yup
    .string()
    .matches(URL_YOUTUBE_REG, "Wrong Format URL")
    .required("Please fill the link"),
});

const YoutubeVideoEditorModal: React.FC<YoutubeVideoEditorModalProps> = ({
  show,
  isEdit,
  item,
  toggleModal,
  onConfirmCallback,
}) => {
  const [initialValues, setInitialValues] = useState<YoutubeVideoItem>(
    initialYoutubeVideoValues
  );
  useEffect(() => {
    if (!show) return;
    if (isEdit && item) {
      setInitialValues({
        ...pick(item, ["id", "url"]),
        visible: item.visible,
      });
    } else {
      setInitialValues(initialYoutubeVideoValues);
    }
  }, [show, isEdit, item]);

  const handleSubmit = async (formProps: YoutubeVideoEditorModalFormValues) => {
    try {
      const response = await YoutubeOembed.metadata(formProps.url as string);
      if (response && "ok" in response) {
        const data = {
          metadata: response.data as any,
          url: formProps.url,
          order: item?.order,
          visible: item?.visible as boolean,
        };
        onConfirmCallback(data);
      } else {
        if (response?.kind === "unauthorized") {
          throw new Error(
            "Embedding this video has been disabled by the creator"
          );
        } else {
          throw new Error("YouTube link is wrong");
        }
      }
    } catch (error: any) {
      notification.error({ message: error.message });
    }
  };

  return (
    <React.Fragment>
      <Modal
        width={664}
        closable
        centered
        className="item-editor-modal"
        title={isEdit ? "Edit YouTube Link" : "Add New YouTube Link"}
        visible={show}
        onCancel={() => toggleModal(false)}
        destroyOnClose
        maskClosable={false}
      >
        <div>
          <Formik
            initialValues={initialValues}
            onSubmit={handleSubmit}
            validationSchema={validateSchema}
          >
            {(props) => (
              <React.Fragment>
                <YoutubeVideoEditorForm {...props} />

                <div className="youtube-video-editor__actions m__t--16">
                  <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()}
                  >
                    {isEdit ? "Save" : "Done"}
                  </Button>
                </div>
              </React.Fragment>
            )}
          </Formik>
        </div>
      </Modal>
    </React.Fragment>
  );
};

export default YoutubeVideoEditorModal;
