import { YouTubeShortIndividualVideoModal } from "@komi-app/creator-ui";
import { URL_YOUTUBE_REG, URL_YOUTUBE_SHORT_REG } from "constants/regexp";
import pick from "lodash/pick";
import { YoutubeVideoItem } from "models/talent/talent-profile-module.model";
import React, { useEffect, useState } from "react";
import YoutubeOembed from "services/api/youtube-metadata.api";
import notification from "utils/notification";

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

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

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

const YoutubeShortEditorModal: React.FC<YoutubeShortEditorModalProps> = ({
  show,
  isEdit,
  item,
  toggleModal,
  onConfirmCallback,
}) => {
  const [initialValues, setInitialValues] = useState<YoutubeVideoItem>(
    initialYoutubeShortValues
  );
  const [error, setError] = useState("");
  const [url, setUrl] = useState(initialValues.url);

  useEffect(() => {
    if (!show) return;
    if (isEdit && item) {
      setInitialValues({
        ...pick(item, ["id", "url"]),
        visible: item.visible,
      });
      setUrl(item.url);
    } else {
      setInitialValues(initialYoutubeShortValues);
      setUrl(initialYoutubeShortValues.url);
    }
  }, [show, isEdit, item]);

  useEffect(() => {
    if(!url) {
      return;
    }
    if (!URL_YOUTUBE_REG.test(url) || !URL_YOUTUBE_SHORT_REG.test(url)) {
      return setError("Enter a YouTube Short link");
    }
    return setError("");
  }, [url]);

  const closeModal = () => {
    setError("");
    toggleModal(false);
  }

  const handleSubmit = async () => {
    try {
      if(!!error) return;
      const response = await YoutubeOembed.metadata(url as string);
      if (response && "ok" in response) {
        const data = {
          metadata: response.data as any,
          url: url,
          order: item?.order,
          visible: item?.visible as boolean,
        };
        onConfirmCallback(data);
      } else {
        if (response?.kind === "unauthorized") {
          return setError("Embedding this video has been disabled by the creator");
        } else {
          return setError("Enter a valid YouTube Short link");
        }
      }
    } catch (error: any) {
      notification.error({ message: error.message });
    }
  };

  return (
    <React.Fragment>
      <YouTubeShortIndividualVideoModal
        onSubmit={handleSubmit} 
        onCancel={closeModal} 
        onLinkChange={(link) => setUrl(link.trim())}
        visible={show}
        helper={"Add link to single YouTube Short"}
        error={error}
        disabled={false}
        link={url || ''}/>
    </React.Fragment>
  );
};

export default YoutubeShortEditorModal;
