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 } 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';


export const FundAccountTransferRequestPage = () => {
  const { navigate } = useNavigate();
  const midOptions = useStore.getState().UserStore.selectOptionsMids;
  const userMid = useStore.getState().UserStore.mid;

  const [mid, setMid] = useState<string>(userMid);
  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);
  });

  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 {
        snackBar("이체등록이 실패하였습니다.")
      }
    });
  };

  const isFormValid = () => {
    return (
      mid.trim() !== '' &&
      bankCode.trim() !== '' &&
      accountNo.trim() !== '' &&
      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)}>
                      {
                        midOptions.map((value, index) => (
                          <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>
                      {/* TODO: 은행 목록 옵션 추가 필요 */}
                    </select>
                  </div>
                </div>
                <div className="billing-row">
                  <div className="billing-label">계좌번호<span>*</span></div>
                  <div className="billing-field">
                    <input
                      type="text"
                      value={accountNo}
                      onChange={(e) => setAccountNo(e.target.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) => setAccountName(e.target.value)}
                    />
                  </div>
                </div>
                <div className="billing-row">
                  <div className="billing-label">이체금액<span>*</span></div>
                  <div className="billing-field">
                    <input
                      type="text"
                      value={amount}
                      onChange={(e) => setAmount(parseInt(e.target.value))}
                    />
                  </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) => 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>
    </>
  );
};