import { URLS } from "../api/apiConfig";
import { TAxios } from "../api/TAxios";
import { convertUtcToLocal } from "../components/MediaPlayer/util";
import {
  CATEGORY_DATA_MAX_RESULTS_LIMIT,
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
} from "../utils/Config";
import * as HelperMethods from "../utils/helperMethods";
import { types } from "./actionTypes";
import {
  addReservation,
  changeAppStatus,
  deleteReservation,
} from "./commonActions";

//IF-LGSP-007
export const getMainLiveShow = (props) => (dispatch, getState) => {
  const vodIncFlag = props?.vodIncFlag;

  const onSuccess = (response) => {
    console.log("@@ getMainLiveShow onSuccess", response.data);

    dispatch({
      type: types.GET_MAIN_LIVE_SHOW,
      payload: response.data.data,
    });
  };

  const onFail = (error) => {
    console.error("@@ getMainLiveShow onFail", error);
  };

  TAxios(
    dispatch,
    getState,
    "get",
    URLS.GET_MAIN_LIVE_SHOW,
    { vodIncFlag },
    {},
    onSuccess,
    onFail
  );
};

// Live 알람 설정/해제 IF-LGSP-012
export const setMainLiveUpcomingAlarm = (props) => (dispatch, getState) => {
  const {
    alamDispFlag,
    chanId,
    endDt,
    patnrId,
    patncNm,
    showId,
    showNm,
    strtDt,
  } = props;

  const onSuccess = (response) => {
    console.log("setMainLiveUpcomingAlarm onSuccess", response.data);

    if (alamDispFlag === "Y") {
      const convertedStrtDt = convertUtcToLocal(strtDt);

      const data = {
        startTime: {
          year: convertedStrtDt.getFullYear(),
          month: convertedStrtDt.getMonth() + 1,
          day: convertedStrtDt.getDate(),
          hour: convertedStrtDt.getHours(),
          minute: convertedStrtDt.getMinutes(),
          second: convertedStrtDt.getSeconds(),
        },
        params: {
          message: `[${patncNm}] ${showNm}\n${HelperMethods.$L("Watch Now!")}`,
          buttons: [
            {
              label: HelperMethods.$L("yes"),
            },
            {
              label: HelperMethods.$L("no"),
            },
          ],
          launch: {
            contentTarget: `V3_8002_Tv_FB_${patnrId}`,
          },
          showId: showId,
          chanId: chanId,
        },
      };

      dispatch(addReservation(data));
    }
    //
    else if (alamDispFlag === "N") {
      dispatch(deleteReservation(showId));
    }
  };

  const onFail = (error) => {
    console.error("setMainLiveUpcomingAlarm onFail", error);
  };

  TAxios(
    dispatch,
    getState,
    "post",
    URLS.SET_MAIN_LIVE_UPCOMING_ALARM,
    {},
    { alamDispFlag, endDt, patnrId, showId, strtDt },
    onSuccess,
    onFail
  );
};

// 디테일상품 조회 LF-LGSP-015
export const getMainCategoryDetail = (props) => (dispatch, getState) => {
  const { patnrId, prdtId, liveReqFlag } = props;

  dispatch(changeAppStatus({ showLoadingPanel: { show: true, type: "wait" } }));

  const onSuccess = (response) => {
    console.log("getMainCategoryDetail onSuccess ", response.data);

    dispatch({
      type: types.GET_PRODUCT_DETAIL,
      payload: response.data.data,
    });

    dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
  };

  const onFail = (error) => {
    console.error("getMainCategoryDetail onFail", error);
    dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
  };

  TAxios(
    dispatch,
    getState,
    "get",
    URLS.GET_PRODUCT_DETAIL,
    { patnrId, prdtId, liveReqFlag },
    {},
    onSuccess,
    onFail
  );
};

// 영상 상세 보기 조회 LF-LGSP-047
export const getMainCategoryShowDetail = (props) => (dispatch, getState) => {
  const { patnrId, showId, curationId } = props;
  const onSuccess = (response) => {
    console.log("getMainCategoryShowDetail onSuccess ", response.data);

    dispatch({
      type: types.GET_MAIN_CATEGORY_SHOW_DETAIL,
      payload: response.data.data,
    });
  };

  const onFail = (error) => {
    console.error("getMainCategoryShowDetail onFail", error);
  };

  TAxios(
    dispatch,
    getState,
    "get",
    URLS.GET_MAIN_CATEGORY_SHOW_DETAIL,
    { patnrId, showId, curationId },
    {},
    onSuccess,
    onFail
  );
};

// 서브카테고리 조회 IF-LGSP-051
let getSubCategoryKey = null;
let lastSubCategoryParams = {};
export const getSubCategory =
  (params, pageNo = 1, key = null, clear = false) =>
  (dispatch, getState) => {
    const { lgCatCd, patnrIdList, tabType, filterType } = params;
    let pageSize = params.pageSize || CATEGORY_DATA_MAX_RESULTS_LIMIT;

    if (pageNo === 1) {
      if (
        lastSubCategoryParams &&
        JSON.stringify(lastSubCategoryParams) === JSON.stringify(params)
      ) {
        console.log("getSubCategory ignore patch");
        return;
      }
      lastSubCategoryParams = { ...params };
      if (clear) {
        dispatch(clearSubCategory());
      }
    }

    let currentKey = key;
    const onSuccess = (response) => {
      console.log("getSubCategory onSuccess ", response.data);

      if (pageNo === 1) {
        getSubCategoryKey = new Date();
        currentKey = getSubCategoryKey;
        dispatch({
          type: types.GET_SUB_CATEGORY,
          payload: response.data.data,
          categoryParams: {
            lgCatCd,
            patnrIdList,
            tabType,
            filterType,
            pageSize,
          },
        });
      } else if (getSubCategoryKey === currentKey) {
        dispatch({
          type: types.GET_SUB_CATEGORY,
          payload: response.data.data,
          append: true,
          startIndex: (pageNo - 1) * pageSize,
        });
      }
    };

    const onFail = (error) => {
      console.error("getSubCategory onFail", error);
      if (pageNo === 1) {
        lastSubCategoryParams = {};
      }
    };

    TAxios(
      dispatch,
      getState,
      "get",
      URLS.GET_SUB_CATEGORY,
      { lgCatCd, patnrIdList, pageSize, pageNo, tabType, filterType },
      {},
      onSuccess,
      onFail
    );
  };

export const continueGetSubCategory = (key, pageNo) => (dispatch, getState) => {
  if (!lastSubCategoryParams) {
    console.warn("No previous category parameters found");
    return;
  }

  const subCategoryData = getState().main.subCategoryData;
  const targetData =
    subCategoryData[key]?.subCatItemList ||
    subCategoryData[key]?.subCatShowList ||
    [];
  const totalCount = subCategoryData[key]?.total ?? 0;
  const startIndex = CATEGORY_DATA_MAX_RESULTS_LIMIT * (pageNo - 1);
  if (
    (startIndex <= 1 && !targetData) ||
    startIndex < targetData.length ||
    totalCount - 1 <= startIndex
  ) {
    //ignore query
    return;
  }
  dispatch(
    getSubCategory({ ...lastSubCategoryParams }, pageNo, getSubCategoryKey)
  );
};

const clearSubCategory = () => ({
  type: types.CLEAR_SUB_CATEGORY,
});

// TOP20 영상 목록 조회 IF-LGSP-069
export const getTop20Show = () => (dispatch, getState) => {
  const onSuccess = (response) => {
    console.log("getTop20Show onSuccess ", response.data);

    dispatch({
      type: types.GET_TOP_20_SHOW,
      payload: response.data.data,
    });
    dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
  };

  const onFail = (error) => {
    console.error("getTop20Show onFail", error);
    dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
  };

  TAxios(
    dispatch,
    getState,
    "get",
    URLS.GET_TOP20_SHOW,
    {},
    {},
    onSuccess,
    onFail
  );
};

// 유메이라이크 아이템 리스트 IF-LGSP-201
export const getMainYouMayLike =
  ({ lgCatCd, exclCurationId, exclPatnrId, exclPrdtId, catDpTh3, catDpTh4 }) =>
  (dispatch, getState) => {
    const onSuccess = (response) => {
      console.log("getMainYouMayLike onSuccess ", response.data);

      dispatch({
        type: types.GET_YOUMAYLIKE,
        payload: response.data.data,
      });
    };

    const onFail = (error) => {
      console.error("getMainYouMayLike onFail", error);
    };

    TAxios(
      dispatch,
      getState,
      "get",
      URLS.GET_YOUMAYLIKE,
      { lgCatCd, catDpTh3, catDpTh4, exclCurationId, exclPatnrId, exclPrdtId },
      {},
      onSuccess,
      onFail
    );
  };

// 찜 여부 확인 IF-LGSP-075
export const getMyFavoriteFlag = (params) => (dispatch, getState) => {
  const { patnrId, prdtId } = params;

  const onSuccess = (response) => {
    console.log("getMyFavoriteFlag onSuccess ", response.data);
    dispatch({
      type: types.GET_MY_FAVORITE_FLAG,
      payload: response.data.data,
    });
  };
  const onFail = (error) => {
    console.error("getMyFavoriteFlag onFail", error);
  };

  TAxios(
    dispatch,
    getState,
    "get",
    URLS.GET_MY_FAVORITE_FLAG,
    { patnrId, prdtId },
    {},
    onSuccess,
    onFail
  );
};
// 상품 찜하기 IF-LGSP-014
export const setMainLikeCategory = (params) => (dispatch, getState) => {
  const { patnrId, prdtId } = params;

  const onSuccess = (response) => {
    console.log("setMainLikeCategory onSuccess ", response.data);
    dispatch({
      type: types.SET_MAIN_LIKE_CATEGORY,
      payload: response.data.data,
    });
  };
  const onFail = (error) => {
    console.error("setMainLikeCategory onFail", error);
  };

  TAxios(
    dispatch,
    getState,
    "post",
    URLS.SET_MAIN_LIKE_CATEGORY,
    {},
    { patnrId, prdtId },
    onSuccess,
    onFail
  );
};

// HOME Live Full 영상 상세 보기 정보 조회 IF-LGSP-302
export const getHomeFullVideoInfo =
  ({ lgCatCd }) =>
  (dispatch, getState) => {
    const onSuccess = (response) => {
      console.log(
        "getHomeFullVideoInfo onSuccess",
        response.data.data.showInfos
      );

      dispatch({
        type: types.GET_HOME_FULL_VIDEO_INFO,
        payload: { data: response.data.data, lgCatCd },
      });
    };

    const onFail = (error) => {
      console.error("getHomeFullVideoInfo onSuccess", error);
    };

    TAxios(
      dispatch,
      getState,
      "get",
      URLS.GET_HOME_FULL_VIDEO_INFO,
      { lgCatCd },
      {},
      onSuccess,
      onFail
    );
  };

// 메인화면 Live 현재 방송 상품 조회 IF-LGSP-046
export const getMainLiveShowNowProduct =
  ({ patnrId, showId, lstChgDt }) =>
  (dispatch, getState) => {
    const onSuccess = (response) => {
      console.log("getMainLiveShowNowProduct onSuccess", response.data);

      dispatch({
        type: types.GET_MAIN_LIVE_SHOW_NOW_PRODUCT,
        payload: response.data.data,
      });
    };

    const onFail = (error) => {
      console.error("getMainLiveShowNowProduct onFail", error);
    };

    TAxios(
      dispatch,
      getState,
      "get",
      URLS.GET_MAIN_LIVE_SHOW_NOW_PRODUCT,
      { patnrId, showId, lstChgDt },
      {},
      onSuccess,
      onFail
    );
  };

export const clearShopNowInfo = () => {
  return {
    type: types.CLEAR_SHOPNOW_INFO,
  };
};
