import { URLS } from "../api/apiConfig";
import { TAxios } from "../api/TAxios";
import { types } from "./actionTypes";
import {
  changeAppStatus,
  deleteReservation,
  disableNotification,
  enableNotification,
} from "./commonActions";

// 추천 Keyword 목록 조회 IF-LGSP-055
export const getMyRecommandedKeyword = () => (dispatch, getState) => {
  const onSuccess = (response) => {
    console.log("getMyRecommandedKeyword onSuccess ", response.data);

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

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

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

// FAQ 조회 (IF-LGSP-048)
export const getMyFaqInfo = () => (dispatch, getState) => {
  const onSuccess = (response) => {
    console.log("getMyFaqInfo onSuccess ", response.data);
    dispatch({
      type: types.GET_MY_FAQ_INFO,
      payload: response.data.data,
    });
  };

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

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

// Notice 조회 (IF-LGSP-049)
export const getNotice = () => (dispatch, getState) => {
  const onSuccess = (response) => {
    console.log("getMyNotice onSuccess ", response.data);
    dispatch({
      type: types.GET_NOTICE,
      payload: response.data.data,
    });
  };

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

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

// MyPage 파트너사 Contact 정보 조회 (IF-LGSP-033)
export const getMyCustomers = () => (dispatch, getState) => {
  const onSuccess = (response) => {
    console.log("getMyCustomers onSuccess ", response.data);
    dispatch({
      type: types.GET_MY_CUSTOMERS,
      payload: response.data.data,
    });
  };

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

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

// MyPage 찜 목록 IF-LGSP-052
export const getMyFavorite = () => (dispatch, getState) => {
  dispatch(changeAppStatus({ showLoadingPanel: { show: true, type: "wait" } }));

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

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

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

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

// MyPage 찜 삭제 IF-LGSP-053
export const deleteMyFavorite = (params) => (dispatch, getState) => {
  const { productList, showList } = params;

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

    const { favoriteData } = getState().myPage;
    const currentFavorites = favoriteData.favorites;

    if (currentFavorites) {
      const productIdsToDelete = productList.map((item) => item.prdtId);
      const showIdsToDelete = showList.map((item) => item.showId);

      const updatedFavorites = currentFavorites.filter(
        (item) =>
          !productIdsToDelete.includes(item.prdtId) &&
          !showIdsToDelete.includes(item.showId)
      );

      dispatch({
        type: types.DELETE_MY_FAVORITE,
        payload: updatedFavorites,
      });
    }
  };

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

  TAxios(
    dispatch,
    getState,
    "post",
    URLS.DELETE_MY_FAVORITE,
    {},
    { productList, showList },
    onSuccess,
    onFail
  );
};

// MyPage 약관 철회 (IF-LGSP-032)
export const setMyTermsWithdraw =
  (params, callback) => (dispatch, getState) => {
    let localMacAddress;
    const { mandatoryIncludeYn, termsList } = params;

    // 약관철회 파라미터 추가 로그 요청
    const httpHeader = getState().common.httpHeader;
    const macAddress = getState().common.macAddress;
    const userNumber = getState().common.appStatus.loginUserData?.userNumber;

    const macAddr = macAddress?.wired || macAddress?.wifi || macAddress?.p2p;

    if (typeof window === "object" && !window.PalmSystem) {
      localMacAddress = "00:1A:2B:3C:4D:5E";
    }
    const logCreateTime = new Date().toISOString();
    const xDeviceProduct = httpHeader["X-Device-Product"] || httpHeader.prod_cd;

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

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

      if (callback) callback(response.data);
    };

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

    const requestData = {
      mandatoryIncludeYn,
      termsList,
      xDeviceProduct,
      macAddr: macAddr ? macAddr : localMacAddress,
      userNumber: userNumber || "",
      requestTime: logCreateTime,
    };

    TAxios(
      dispatch,
      getState,
      "post",
      URLS.SET_MY_TERMS_WITHDRAW,
      {},
      requestData,
      onSuccess,
      onFail
    );
  };

// MyPage 약관 동의 (IF-LGSP-031)
export const setMyPageTermsAgree =
  (params, callback) => (dispatch, getState) => {
    const { termsList, notTermsList } = params;

    dispatch({ type: types.GET_TERMS_AGREE_YN_START });

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

      // 약관 ID를 약관 코드로 변환하기 위해 state에서 termsIdMap 조회
      const termsIdMap = getState().home.termsIdMap || {};
      const idToCodeMap = Object.entries(termsIdMap).reduce(
        (acc, [code, id]) => {
          acc[id] = code;
          return acc;
        },
        {}
      );

      // 동의한 약관 ID 목록을 약관 코드로 변환
      const agreedTermCodes = termsList
        .map((id) => idToCodeMap[id])
        .filter(Boolean);

      dispatch({
        type: types.SET_MYPAGE_TERMS_AGREE_SUCCESS,
        payload: {
          ...response.data,
          agreedTermCodes: agreedTermCodes, // 변환된 약관 코드 리스트를 payload에 추가
        },
        retCode: response.data.retCode,
      });

      if (callback) callback(response.data);
    };

    const onFail = (error) => {
      console.error("setMyPageTermsAgree onFail ", error);
      dispatch({
        type: types.SET_MYPAGE_TERMS_AGREE_FAIL,
        payload: error,
      });
    };

    TAxios(
      dispatch,
      getState,
      "post",
      URLS.SET_MYPAGE_TERMS_AGREE,
      {},
      { termsList, notTermsList },
      onSuccess,
      onFail
    );
  };

// MyPage Upcoming Alert 정보 변경 조회 (IF-LGSP-050)
export const getMyUpcomingChangeInfo = () => (dispatch, getState) => {
  const onSuccess = (response) => {
    console.log("getMyUpcomingChangeInfo onSuccess ", response.data);

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

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

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

// MyPage Upcoming Alert Show 목록 (IF-LGSP-025)
export const getMyUpcomingAlertShow = () => (dispatch, getState) => {
  const onSuccess = (response) => {
    console.log("getMyUpcomingAlertShow onSuccess ", response.data);

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

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

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

// MyPage UpComing Alert Show 삭제 (IF-LGSP-042)
export const deleteMyUpcomingAlertShow = (params) => (dispatch, getState) => {
  const { showList } = params;

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

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

    for (let index = showList.length; index--; ) {
      dispatch(deleteReservation(showList[index].showId));
    }
  };

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

  TAxios(
    dispatch,
    getState,
    "post",
    URLS.DELETE_MY_UPCOMING_ALERT_SHOW,
    {},
    { showList },
    onSuccess,
    onFail
  );
};

// MyPage Upcoming Alert Show - Key 목록 (IF-LGSP-076)
export const getMyUpcomingAlertShowKeys = () => (dispatch, getState) => {
  const onSuccess = (response) => {
    console.log("getMyUpcomingAlertShowKeys onSuccess ", response.data);

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

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

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

// MyPage Upcoming Alert 수신 여부 설정 (IF-LGSP-029)
export const setMyUpcomingUseAlert = (params) => (dispatch, getState) => {
  const { upcomingAlamUseFlag } = params;

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

    if (upcomingAlamUseFlag === "Y") {
      dispatch(enableNotification());
    } else {
      dispatch(disableNotification());
    }

    dispatch({
      type: types.SET_MY_UPCOMING_USE_ALERT,
      payload: upcomingAlamUseFlag,
    });
  };

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

    if (upcomingAlamUseFlag === "Y") {
      dispatch(disableNotification());
    } else {
      dispatch(enableNotification());
    }
  };

  TAxios(
    dispatch,
    getState,
    "post",
    URLS.SET_MY_UPCOMING_USE_ALERT,
    {},
    { upcomingAlamUseFlag },
    onSuccess,
    onFail
  );
};

// UpComing Alert 방송 변경 정보 조회 (IF-LGSP-068)
export const getUpcomingAlertShowChangeInfo = () => (dispatch, getState) => {
  const onSuccess = (response) => {
    console.log("getUpcomingAlertShowChangeInfo onSuccess ", response.data);

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

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

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

// Recently Viewed 정보 요청 조회 (IF-LGSP-059)
export const getMyRecentlyViewedInfo = (params) => (dispatch, getState) => {
  const { showList, productList } = params;

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

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

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

  TAxios(
    dispatch,
    getState,
    "post",
    URLS.GET_MY_RECENTLY_VIEWED_INFO,
    {},
    { showList, productList },
    onSuccess,
    onFail
  );
};

export const clearRecentlyViewedInfo = () => ({
  type: types.CLEAR_RECENTLY_VIEWED_INFO,
});

export const clearFavorites = () => ({
  type: types.CLEAR_FAVORITES,
});
