import { ChangeEvent, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PATHS } from '@/shared/constants/paths';
import { useLocation } from 'react-router';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useExtensionArsApplyMutation } from '@/entities/additional-service/api/ars/use-extension-ars-apply-mutation';
import { HeaderType } from '@/entities/common/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { ArsPaymentMethod, ExtensionArsApplyParams, ExtensionArsApplyResponse } from '@/entities/additional-service/model/ars/types';
import { ArsRequestSuccessPage } from './request-success-page';
import { useStore } from '@/shared/model/store';
import { snackBar } from '@/shared/lib';
import { NumericFormat, PatternFormat } from 'react-number-format';
import { showAlert } from '@/widgets/show-alert';
import { useKeyboardAware } from '@/shared/lib/hooks/use-keyboard-aware';

export const ArsRequestPage = () => {
  const { t } = useTranslation();
  const { navigate } = useNavigate();
  const location = useLocation();

  const midOptions = useStore.getState().UserStore.selectOptionsMids

  const { mid: receivedMid } = location.state || {};

  const { mutateAsync: arsApply } = useExtensionArsApplyMutation();

  const [mid, setMid] = useState<string>(receivedMid || '');
  const [moid, setMoid] = useState<string>('');
  const [goodsName, setGoodsName] = useState<string>('');
  const [amount, setAmount] = useState<number>(0);
  const [instmntMonth, setInstmntMonth] = useState<string>('00');
  const [buyerName, setBuyerName] = useState<string>('');
  const [phoneNumber, setPhoneNumber] = useState<string>('');
  const [email, setEamil] = useState<string>('');
  const [arsPaymentMethod, setArsPaymentMethod] = useState<ArsPaymentMethod>(ArsPaymentMethod.SMS);
  const [successPageOn, setSuccessPageOn] = useState<boolean>(false);
  const [resultMessage, setResultMessage] = useState<string>('');

  const { handleInputFocus, keyboardAwarePadding } = useKeyboardAware();

  useSetHeaderTitle(t('additionalService.ars.paymentRequest'));
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.additionalService.ars.list);
  });

  const callArsApply = () => {
    let arsApplyParams: ExtensionArsApplyParams = {
      mid: mid,
      moid: moid,
      goodsName: goodsName,
      amount: amount,
      instmntMonth: instmntMonth,
      buyerName: buyerName,
      phoneNumber: phoneNumber,
      email: email,
      arsPaymentMethod: arsPaymentMethod,
    };
    arsApply(arsApplyParams)
      .then((rs: ExtensionArsApplyResponse) => {
        if (rs.status) {
          setSuccessPageOn(true);
        } else {
          const errorMessage = rs.error?.message || t('additionalService.ars.requestFailed');
          snackBar(`[${t('common.failed')}] ${errorMessage}`);
        }
      })
      .catch((e) => {
        const errorMsg = e?.response?.data?.message || e?.response?.data?.error?.message || t('additionalService.ars.requestFailed');
        if (e.response?.data?.error?.root !== "SystemErrorCode") {
          snackBar(`[${t('common.failed')}] ${errorMsg}`);
        } else {
          showAlert(`[${t('common.failed')}] ${errorMsg}`)
        }
      })

  };

  const onClickToRequest = () => {
    callArsApply();
  };

  const isValidPhoneNumber = (phone: string) => {
    // 한국 휴대폰 번호: 010, 011, 016, 017, 018, 019로 시작, 10-11자리
    const phoneRegex = /^01[0|1|6|7|8|9][0-9]{7,8}$/;
    return phoneRegex.test(phone);
  };

  const isValidEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const isFormValid = () => {
    return (
      mid.trim() !== '' &&
      moid.trim() !== '' &&
      goodsName.trim() !== '' &&
      amount > 0 &&
      buyerName.trim() !== '' &&
      isValidPhoneNumber(phoneNumber)
    );
  };

  const getArsPaymentMethodBtns = () => {
    let rs = [];
    rs.push(
      <div
        key="ars-payment-method-btns"
        className="seg-buttons"
      >
        <button
          className={`btn-36 light ${(arsPaymentMethod === ArsPaymentMethod.SMS) ? 'btn-blue' : 'btn-white'}`}
          onClick={(e) => setArsPaymentMethod(ArsPaymentMethod.SMS)}
        >{ArsPaymentMethod.SMS}</button>
        <button
          className={`btn-36 light ${(arsPaymentMethod === ArsPaymentMethod.ARS) ? 'btn-blue' : 'btn-white'}`}
          onClick={(e) => setArsPaymentMethod(ArsPaymentMethod.ARS)}
        >{ArsPaymentMethod.ARS}</button>
      </div>
    );
    return rs;
  };

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="option-list">
              <div className="billing-form gap-16">
                <div className="billing-row">
                  <div className="billing-label">{t('additionalService.ars.merchant')} <span>*</span></div>
                  <div className="billing-field">
                    <select
                      value={mid}
                      onChange={(e: ChangeEvent<HTMLSelectElement>) => setMid(e.target.value)}
                    >
                      {
                        midOptions.map((value) => (
                          <option
                            key={value.value}
                            value={value.value}
                          >{value.name}</option>
                        ))
                      }
                    </select>
                  </div>
                </div>

                <div className="billing-row">
                  <div className="billing-label">{t('additionalService.ars.orderNumber')} <span>*</span></div>
                  <div className="billing-field">
                    <input
                      type="text"
                      value={moid}
                      onChange={(e: ChangeEvent<HTMLInputElement>) => setMoid(e.target.value)}
                      onFocus={handleInputFocus}
                    />
                  </div>
                </div>

                <div className="billing-row">
                  <div className="billing-label">{t('additionalService.ars.productName')} <span>*</span></div>
                  <div className="billing-field">
                    <input
                      type="text"
                      value={goodsName}
                      onChange={(e: ChangeEvent<HTMLInputElement>) => setGoodsName(e.target.value)}
                      onFocus={handleInputFocus}
                    />
                  </div>
                </div>

                <div className="billing-row">
                  <div className="billing-label">{t('additionalService.ars.amount')} <span>*</span></div>
                  <div className="billing-field">
                    <NumericFormat
                      value={amount}
                      thousandSeparator={true}
                      allowNegative={false}
                      displayType="input"
                      onValueChange={(values) => {
                        const { floatValue } = values;
                        setAmount(floatValue ?? 0);
                      }}
                      onFocus={handleInputFocus}
                    ></NumericFormat>
                  </div>
                </div>

                <div className="billing-row">
                  <div className="billing-label">{t('additionalService.ars.installmentPeriod')} <span>*</span></div>
                  <div className="billing-field">
                    <select
                      disabled
                      value={instmntMonth}
                      onChange={(e: ChangeEvent<HTMLSelectElement>) => setInstmntMonth(e.target.value)}
                    >
                      <option value="00">{t('additionalService.ars.lumpSum')}</option>
                    </select>
                  </div>
                </div>

                <div className="billing-row">
                  <div className="billing-label">{t('additionalService.ars.buyerName')} <span>*</span></div>
                  <div className="billing-field">
                    <input
                      type="text"
                      value={buyerName}
                      onChange={(e: ChangeEvent<HTMLInputElement>) => setBuyerName(e.target.value)}
                      onFocus={handleInputFocus}
                    />
                  </div>
                </div>

                <div className="billing-row">
                  <div className="billing-label">{t('additionalService.ars.phoneNumber')} <span>*</span></div>
                  <div className="billing-field">
                    <input
                      type="tel"
                      value={phoneNumber}
                      placeholder='01012345678'
                      onChange={(e: ChangeEvent<HTMLInputElement>) => {
                        const onlyNumbers = e.target.value.replace(/[^0-9]/g, '');
                        setPhoneNumber(onlyNumbers);
                      }}
                      className={phoneNumber && !isValidPhoneNumber(phoneNumber) ? 'error' : ''}
                      inputMode="numeric"
                      pattern="[0-9]*"
                      maxLength={11}
                      onFocus={handleInputFocus}
                    />
                  </div>
                </div>

                <div className="billing-row">
                  <div className="billing-label">{t('additionalService.ars.email')}</div>
                  <div className="billing-field">
                    <input
                      type="text"
                      value={email}
                      placeholder='test@nicepay.co.kr'
                      onChange={(e: ChangeEvent<HTMLInputElement>) => setEamil(e.target.value)}
                      className={email && !isValidEmail(email) ? 'error' : ''}
                      onFocus={handleInputFocus}
                    />
                  </div>
                </div>

                <div className="billing-row" style={keyboardAwarePadding}>
                  <div className="billing-label">{t('additionalService.ars.paymentMethod')} <span>*</span></div>
                  <div className="billing-field">
                    {getArsPaymentMethodBtns()}
                  </div>
                </div>
              </div>
            </div>
            <div className="apply-row">
              <button
                className="btn-50 btn-blue flex-1"
                onClick={() => onClickToRequest()}
                disabled={!isFormValid()}
              >{t('additionalService.ars.paymentRequest')}</button>
            </div>
          </div>
        </div>
      </main>

      <ArsRequestSuccessPage
        pageOn={successPageOn}
        setPageOn={setSuccessPageOn}
        resultMessage={resultMessage}
      />
    </>
  );
};