import { Modal } from "antd";
import { Icon } from "components/Icon";
import { YOUTUBE_MODAL_STEP, YOUTUBE_TYPE } from "constants/module";
import { YoutubeItem } from "models/talent/talent-profile-module.model";
import * as React from "react";
import { useCallback, useState } from "react";
import { talentService } from "services";
import YoutubeOembed from "services/api/youtube-metadata.api";
import notification from "utils/notification";
import pick from "lodash/pick";

import "./index.scss";
import collectionYoutube from "./steps/collectionYoutube";
import individualYoutube from "./steps/individualYoutube";
import selectYoutubeType from "./steps/selectYoutubeType";

interface YoutubeModalProps {
  show?: boolean;
  setStatusModal: React.Dispatch<React.SetStateAction<any>>;
  step?: YOUTUBE_MODAL_STEP;
  onSubmit?: (values: any) => void;
  item?: YoutubeItem;
  cancellable?: boolean;
}

const YoutubeModal = ({
  show,
  setStatusModal,
  step = YOUTUBE_MODAL_STEP.SELECT_YOUTUBE_TYPE,
  onSubmit,
  item,
  cancellable,
}: YoutubeModalProps) => {
  const [loading, setLoading] = useState(false);
  const [selectedType, setSelectedType] = useState(YOUTUBE_TYPE.INDIVIDUAL);

  const handleClose = useCallback(() => {
    setStatusModal({
      visible: false,
      status: YOUTUBE_MODAL_STEP.SELECT_YOUTUBE_TYPE,
      item: undefined,
    });
    setSelectedType(YOUTUBE_TYPE.INDIVIDUAL);
  }, []);
  const handleBack = useCallback(() => {
    setStatusModal((values: any) => ({
      ...values,
      status: YOUTUBE_MODAL_STEP.SELECT_YOUTUBE_TYPE,
    }));
  }, []);
  const onSelectedStep = useCallback(() => {
    setStatusModal((values: any) => ({
      ...values,
      status:
        selectedType === YOUTUBE_TYPE.INDIVIDUAL
          ? YOUTUBE_MODAL_STEP.INDIVIDUAL_VIDEO
          : YOUTUBE_MODAL_STEP.VIDEO_COLLECTION,
    }));
  }, [selectedType]);
  const handleIndividualYoutube = async (values: any, action: any) => {
    try {
      setLoading(true);
      const response = await YoutubeOembed.metadata(values.url as string);

      if (response && "ok" in response) {
        const data = {
          metadata: pick(response.data, ["thumbnail_url", "title"]),
          url: values.url,
        };
        onSubmit?.(data);
        handleClose();
        action.resetForm({ url: "" });
        return;
      } 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) {
      action.setErrors({
        url: error.message,
      });
    } finally {
      setLoading(false);
    }
  };
  const handleCollectionYoutube = async (values: any, action: any) => {
    try {
      setLoading(true);
      const result: any = await talentService().getYoutubeCollection(values);

      if (result.ok) {
        onSubmit?.(values);
        handleClose();
        setTimeout(() => {
          action.resetForm({
            url: "",
            totalSelected: 1,
            sort: "newest",
          });
        }, 150);
        return;
      }
      if (result?.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) {
      action.setErrors({
        url: error.message,
      });
    } finally {
      setLoading(false);
    }
  };
  const getView = (value: YOUTUBE_MODAL_STEP) => {
    if (!show) {
      return null;
    }
    const stepMap: any = {
      [YOUTUBE_MODAL_STEP.SELECT_YOUTUBE_TYPE]: () =>
        selectYoutubeType({
          type: selectedType,
          select: setSelectedType,
          close: handleClose,
          callback: onSelectedStep,
        }),
      [YOUTUBE_MODAL_STEP.INDIVIDUAL_VIDEO]: () =>
        individualYoutube({
          loading,
          close: handleClose,
          back: handleBack,
          callback: handleIndividualYoutube,
          item,
          cancellable,
        }),
      [YOUTUBE_MODAL_STEP.VIDEO_COLLECTION]: () =>
        collectionYoutube({
          loading,
          close: handleClose,
          back: handleBack,
          callback: handleCollectionYoutube,
          item,
          cancellable,
        }),
    };

    const make = stepMap[value];

    return make();
  };
  const view = getView(step);

  const title = view?.title || "";
  const content = view?.content;

  const footer = view?.footer || null;

  return (
    <Modal
      closable
      centered
      className="youtube-modal"
      visible={show}
      title={title}
      width={706}
      onCancel={handleClose}
      footer={footer}
      closeIcon={<Icon name="close" />}
    >
      <div className="p__x--24 p__t--24">{content}</div>
    </Modal>
  );
};

export default YoutubeModal;
