import * as _ from 'lodash-es';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useExtensionAlimtalkSettingDetailMutation } from '@/entities/additional-service/api/alimtalk/use-extansion-alimtalk-setting-detail-mutation';
import { useExtensionAlimtalkSettingSaveMutation } from '@/entities/additional-service/api/alimtalk/use-extansion-alimtalk-setting-save-mutation';
import {
  AlimtalkSettingFlagKeys,
  ExtensionAlimtalkSettingDetailParams,
  ExtensionAlimtalkSettingDetailResponse,
  ExtensionAlimtalkSettingSaveParams,
  SendMerchantInfo,
  SendUserInfo
} from '@/entities/additional-service/model/alimtalk/types';
import { useEffect, useState } from 'react';
import { AlimTalkSettingServiceRow } from '@/entities/additional-service/ui/alimtalk/setting-service-row';
import { useStore } from '@/shared/model/store';
import { snackBar } from '@/shared/lib';

export const AlimtalkSettingPage = () => {
  const { navigate } = useNavigate();
  const midOptionsWithoutGids = useStore.getState().UserStore.selectOptionsMidsWithoutGids;
  const userMid = useStore.getState().UserStore.mid;

  const [mid, setMid] = useState<string>('');

  const [merchantCardApprovalFlag, setMerchantCardApprovalFlag] = useState<boolean>(false);
  const [merchantCardCancelFlag, setMerchantCardCancelFlag] = useState<boolean>(false);
  const [merchantBankApprovalFlag, setMerchantBankApprovalFlag] = useState<boolean>(false);
  const [merchantBankCancelFlag, setMerchantBankCancelFlag] = useState<boolean>(false);
  const [merchantVirtureAccountDepositRequestFlag, setMerchantVirtureAccountDepositRequestFlag] = useState<boolean>(false);
  const [merchantVirtureAccountDepositCompleteFlag, setMerchantVirtureAccountDepositCompleteFlag] = useState<boolean>(false);
  const [merchantVirtureAccountRefundFlag, setMerchantVirtureAccountRefundFlag] = useState<boolean>(false);

  const [userCardApprovalFlag, setUserCardApprovalFlag] = useState<boolean>(false);
  const [userCardCancelFlag, setUserCardCancelFlag] = useState<boolean>(false);
  const [userBankApprovalFlag, setUserBankApprovalFlag] = useState<boolean>(false);
  const [userBankCancelFlag, setUserBankCancelFlag] = useState<boolean>(false);
  const [userVirtureAccountDepositRequestFlag, setUserVirtureAccountDepositRequestFlag] = useState<boolean>(false);
  const [userVirtureAccountDepositCompleteFlag, setUserVirtureAccountDepositCompleteFlag] = useState<boolean>(false);
  const [userVirtureAccountRefundFlag, setUserVirtureAccountRefundFlag] = useState<boolean>(false);

  const { mutateAsync: alimtalkSettingDetail } = useExtensionAlimtalkSettingDetailMutation();
  const { mutateAsync: alimtalkSettingSave } = useExtensionAlimtalkSettingSaveMutation();

  const callSettingDetail = () => {
    let params: ExtensionAlimtalkSettingDetailParams = {
      mid: mid
    };

    alimtalkSettingDetail(params).then((rs: ExtensionAlimtalkSettingDetailResponse) => {
      let sendMerchantInfo = rs.sendMerchantInfo;
      let sendUserInfo = rs.sendUserInfo;

      if (sendMerchantInfo) {
        setMerchantCardApprovalFlag((sendMerchantInfo?.cardApprovalFlag || false));
        setMerchantCardCancelFlag(sendMerchantInfo?.cardCancelFlag || false);
        setMerchantBankApprovalFlag(sendMerchantInfo?.bankApprovalFlag || false);
        setMerchantBankCancelFlag(sendMerchantInfo?.bankCancelFlag || false);
        setMerchantVirtureAccountDepositRequestFlag(sendMerchantInfo?.virtureAccountDepositRequestFlag || false);
        setMerchantVirtureAccountDepositCompleteFlag(sendMerchantInfo?.virtureAccountDepositCompleteFlag || false);
        setMerchantVirtureAccountRefundFlag(sendMerchantInfo?.virtureAccountRefundFlag || false);
      }
      if (sendUserInfo) {
        setUserCardApprovalFlag(sendUserInfo?.cardApprovalFlag || false);
        setUserCardCancelFlag(sendUserInfo?.cardCancelFlag || false);
        setUserBankApprovalFlag(sendUserInfo?.bankApprovalFlag || false);
        setUserBankCancelFlag(sendUserInfo?.bankCancelFlag || false);
        setUserVirtureAccountDepositRequestFlag(sendUserInfo?.virtureAccountDepositRequestFlag || false);
        setUserVirtureAccountDepositCompleteFlag(sendUserInfo?.virtureAccountDepositCompleteFlag || false);
        setUserVirtureAccountRefundFlag(sendUserInfo?.virtureAccountRefundFlag || false);
      }
    });
  };

  const callSettingSave = () => {
    let params: ExtensionAlimtalkSettingSaveParams = {
      mid: mid,
      sendMerchantInfo: {
        cardApprovalFlag: merchantCardApprovalFlag,
        cardCancelFlag: merchantCardCancelFlag,
        bankApprovalFlag: merchantBankApprovalFlag,
        bankCancelFlag: merchantBankCancelFlag,
        virtureAccountDepositRequestFlag: merchantVirtureAccountDepositRequestFlag,
        virtureAccountDepositCompleteFlag: merchantVirtureAccountDepositCompleteFlag,
        virtureAccountRefundFlag: merchantVirtureAccountRefundFlag
      },
      sendUserInfo: {
        cardApprovalFlag: userCardApprovalFlag,
        cardCancelFlag: userCardCancelFlag,
        bankApprovalFlag: userBankApprovalFlag,
        bankCancelFlag: userBankCancelFlag,
        virtureAccountDepositRequestFlag: userVirtureAccountDepositRequestFlag,
        virtureAccountDepositCompleteFlag: userVirtureAccountDepositCompleteFlag,
        virtureAccountRefundFlag: userVirtureAccountRefundFlag
      },
    };
    alimtalkSettingSave(params)
      .then((rs) => {
        snackBar("저장을 성공하였습니다.");
      })
      .catch((error) => {
        const failReason = error?.response?.data?.message || error?.message || "알 수 없는 오류";
        snackBar(`[실패] ${failReason}`);
      });
  };

  useSetHeaderTitle('알림톡 결제통보');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.additionalService.alimtalk.list);
  });

  const onClickToSave = () => {
    callSettingSave();
  };

  // MID 초기값 설정
  useEffect(() => {
    if (!mid && midOptionsWithoutGids.length > 0) {
      // userMid가 옵션에 있으면 userMid 사용, 없으면 첫 번째 옵션 사용
      const midItem = midOptionsWithoutGids.filter((value) => value.value === userMid);
      const initialMid = (midItem.length > 0) ? userMid : midOptionsWithoutGids[0]?.value || '';
      if (initialMid) {
        setMid(initialMid);
      }
    }
  }, [midOptionsWithoutGids, userMid]);

  // mid가 설정되면 설정 정보 불러오기
  useEffect(() => {
    if (mid) {
      callSettingDetail();
    }
  }, [mid]);

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="option-list">
              <div className="service-settings">
                <div className="service-notice">
                  <div>알림톡을 발송할 대상을 설정할 수 있습니다.</div>
                  <div>알림톡 발송 대상과 유형을 설정해 주세요.</div>
                </div>

                <div className="service-merchant">
                  <div className="service-title">가맹점</div>
                  <div className="service-select">
                    <select
                      value={mid}
                      onChange={(e) => setMid(e.target.value)}>
                      {
                        midOptionsWithoutGids.map((value) => (
                          <option
                            key={value.value}
                            value={value.value}
                          >{value.name}</option>
                        ))
                      }
                    </select>
                    <span className="ic20 arrow-down" aria-hidden="true"></span>
                  </div>
                </div>

                <div className="service-section">
                  <div className="service-row align-right">
                    <span>가맹점에 발송</span>
                    <span>고객에게 발송</span>
                  </div>
                </div>

                <div className="service-section">
                  <AlimTalkSettingServiceRow
                    title='신용카드(승인)'
                    merchantFlag={merchantCardApprovalFlag}
                    userFlag={userCardApprovalFlag}
                    setMerchantFlag={setMerchantCardApprovalFlag}
                    setUserFlag={setUserCardApprovalFlag}
                  ></AlimTalkSettingServiceRow>
                  <AlimTalkSettingServiceRow
                    title='신용카드(취소)'
                    merchantFlag={merchantCardCancelFlag}
                    userFlag={userCardCancelFlag}
                    setMerchantFlag={setMerchantCardCancelFlag}
                    setUserFlag={setUserCardCancelFlag}
                  ></AlimTalkSettingServiceRow>
                  <AlimTalkSettingServiceRow
                    title='계좌이체(승인)'
                    merchantFlag={merchantBankApprovalFlag}
                    userFlag={userBankApprovalFlag}
                    setMerchantFlag={setMerchantBankApprovalFlag}
                    setUserFlag={setUserBankApprovalFlag}
                  ></AlimTalkSettingServiceRow>
                  <AlimTalkSettingServiceRow
                    title='계좌이체(취소)'
                    merchantFlag={merchantBankCancelFlag}
                    userFlag={userBankCancelFlag}
                    setMerchantFlag={setMerchantBankCancelFlag}
                    setUserFlag={setUserBankCancelFlag}
                  ></AlimTalkSettingServiceRow>
                  <AlimTalkSettingServiceRow
                    title='가상계좌(입금요청)'
                    merchantFlag={merchantVirtureAccountDepositRequestFlag}
                    userFlag={userVirtureAccountDepositRequestFlag}
                    setMerchantFlag={setMerchantVirtureAccountDepositRequestFlag}
                    setUserFlag={setUserVirtureAccountDepositRequestFlag}
                  ></AlimTalkSettingServiceRow>
                  <AlimTalkSettingServiceRow
                    title='가상계좌(입금완료)'
                    merchantFlag={merchantVirtureAccountDepositCompleteFlag}
                    userFlag={userVirtureAccountDepositCompleteFlag}
                    setMerchantFlag={setMerchantVirtureAccountDepositCompleteFlag}
                    setUserFlag={setUserVirtureAccountDepositCompleteFlag}
                  ></AlimTalkSettingServiceRow>
                  <AlimTalkSettingServiceRow
                    title='가상계좌(환불)'
                    merchantFlag={merchantVirtureAccountRefundFlag}
                    userFlag={userVirtureAccountRefundFlag}
                    setMerchantFlag={setMerchantVirtureAccountRefundFlag}
                    setUserFlag={setUserVirtureAccountRefundFlag}
                  ></AlimTalkSettingServiceRow>
                </div>
              </div>
            </div>
            <div className="apply-row">
              <button
                className="btn-50 btn-blue flex-1"
                onClick={() => onClickToSave()}
              >저장</button>
            </div>
          </div>
        </div>
      </main>
    </>
  );
};