import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { ChangeEvent, useState, useEffect } from 'react';
import { ExtensionFundAccountTransferRegistParams, ExtensionFundAccountTransferRegistResponse } from '@/entities/additional-service/model/fund-account/types';
import { useStore } from '@/shared/model/store';
import { snackBar } from '@/shared/lib';
import { useExtensionFundAccountTransferRegistMutation } from '@/entities/additional-service/api/fund-account/use-extension-fund-account-transfer-regist-mutation';
import { NumericFormat } from 'react-number-format';
import { useExtensionFundAccountTransferRequestMutation } from '@/entities/additional-service/api/fund-account/use-extension-fund-account-transfer-request-mutation';


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

  const [mid, setMid] = useState<string>('');
  const [bankCode, setBankCode] = useState<string>('');
  const [accountNo, setAccountNo] = useState<string>('');
  const [accountName, setAccountName] = useState<string>('');
  const [amount, setAmount] = useState<number>(0);
  const [moid, setMoid] = useState<string>('');
  const [depositParameter, setDepositParameter] = useState<string>('');

  const { mutateAsync: extensionFundAccountRegist } = useExtensionFundAccountTransferRegistMutation();

  useSetHeaderTitle('자금이체 이체등록');
  useSetHeaderType(HeaderType.RightClose);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.additionalService.fundAccount.transferList);
  });

  // 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]);

  const resetForm = () => {
    setBankCode('');
    setAccountNo('');
    setAccountName('');
    setAmount(0);
    setMoid('');
    setDepositParameter('');
  };

  const callExtensionFundAccountTransferRegist = () => {
    let params: ExtensionFundAccountTransferRegistParams = {
      mid: mid,
      bankCode: bankCode,
      accountNo: accountNo,
      accountName: accountName,
      amount: amount,
      moid: moid,
      depositParameter: depositParameter
    };
    extensionFundAccountRegist(params).then((rs: ExtensionFundAccountTransferRegistResponse) => {
      if (rs.status) {
        snackBar("이체등록을 성공하였습니다.")
        resetForm();
      } else {
        const errorMessage = rs.error?.message || '이체등록이 실패하였습니다.';
        snackBar(`[실패] ${errorMessage}`);
      }
    }).catch((error) => {
      const errorMessage = error?.response?.data?.error?.message ||
        error?.message ||
        '이체등록 중 오류가 발생했습니다.';
      snackBar(`[실패] ${errorMessage}`);
    });
  };

  const isFormValid = () => {
    return (
      mid.trim() !== '' &&
      bankCode.trim() !== '' &&
      accountNo.trim() !== '' &&
      accountNo.length > 9 &&
      accountName.trim() !== '' &&
      amount > 0 &&
      moid.trim() !== ''
    )
  }

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="ing-list">
              <div className="billing-form gap-30">
                <div className="billing-row">
                  <div className="billing-label">가맹점<span>*</span></div>
                  <div className="billing-field">
                    <select
                      value={mid}
                      onChange={(e) => setMid(e.target.value)}>
                      {
                        midOptionsWithoutGids.map((value) => (
                          <option
                            key={value.value}
                            value={value.value}
                          >{value.name}</option>
                        ))
                      }
                    </select>
                  </div>
                </div>
                <div className="billing-row">
                  <div className="billing-label">은행<span>*</span></div>
                  <div className="billing-field">
                    <select value={bankCode} onChange={(e) => setBankCode(e.target.value)}>
                      <option value="">선택하세요</option>
                      {
                        bankList
                          .filter((bank) => bank.code1 !== '****')
                          .map((bank) => (
                            <option
                              key={bank.code1}
                              value={bank.code1}
                            >{bank.desc1}</option>
                          ))
                      }
                    </select>
                  </div>
                </div>
                <div className="billing-row">
                  <div className="billing-label">계좌번호<span>*</span></div>
                  <div className="billing-field">
                    <NumericFormat
                      value={accountNo}
                      valueIsNumericString
                      allowNegative={false}
                      decimalScale={0}
                      isAllowed={(values) => {
                        const { value } = values;
                        return !value || value.length <= 14;
                      }}
                      onValueChange={(values) => setAccountNo(values.value)}
                    />
                  </div>
                </div>
                <div className="billing-row">
                  <div className="billing-label">예금주명<span>*</span></div>
                  <div className="billing-field">
                    <input
                      type="text"
                      value={accountName}
                      onChange={(e: ChangeEvent<HTMLInputElement>) => setAccountName(e.target.value)}
                    />
                  </div>
                </div>
                <div className="billing-row">
                  <div className="billing-label">이체금액<span>*</span></div>
                  <div className="billing-field">
                    <NumericFormat
                      value={amount}
                      allowNegative={false}
                      thousandSeparator={true}
                      displayType='input'
                      onValueChange={(values) => {
                        const { floatValue } = values;
                        setAmount(floatValue ?? 0);
                      }}
                    ></NumericFormat>
                  </div>
                </div>
                <div className="billing-row">
                  <div className="billing-label">주문번호<span>*</span></div>
                  <div className="billing-field" style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                    <input
                      type="text"
                      value={moid}
                      onChange={(e: ChangeEvent<HTMLInputElement>) => setMoid(e.target.value)}
                    />
                  </div>
                </div>
                <div className="billing-row">
                  <div className="billing-label">입금인자</div>
                  <div className="billing-field">
                    <input
                      type="text"
                      value={depositParameter}
                      onChange={(e) => setDepositParameter(e.target.value)}
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
      <div className="apply-row">
        <button
          className="btn-50 btn-blue flex-1"
          onClick={callExtensionFundAccountTransferRegist}
          disabled={!isFormValid()}
        >등록</button>
      </div>
    </>
  );
};