import { useState } from 'react';
import { LinkPaymentStep1 } from '@/entities/additional-service/ui/link-payment/apply/link-payment-step1';
import { LinkPaymentStep2 } from '@/entities/additional-service/ui/link-payment/apply/link-payment-step2';
import { HeaderType } from '@/entities/common/model/types';
import { ProcessStep } from '@/entities/transaction/model/types';
import { useSetFooterMode, useSetHeaderTitle, useSetHeaderType } from '@/widgets/sub-layout/use-sub-layout';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { PATHS } from "@/shared/constants/paths";
import { IdentityType, Language } from '@/entities/additional-service/model/types';
import { LinkContentType, LinkPaymentFormData, LinkPaymentSendMethod } from '@/entities/additional-service/model/link-pay/types';
import { useStore } from '@/shared/model/store';
import moment from 'moment';



export const LinkPaymentApplyPage = () => {
  const { navigate } = useNavigate();

  const midOptionsWithoutGids = useStore.getState().UserStore.selectOptionsMidsWithoutGids;
  const userMid = useStore.getState().UserStore.mid;

  // userMid가 midOptionsWithoutGids에 있으면 userMid 사용, 없으면 첫 번째 옵션 사용
  let midItem = midOptionsWithoutGids.filter((value) => {
    return value.value === userMid;
  });
  const initialMid = (midItem.length > 0) ? userMid : (midOptionsWithoutGids.length > 0 ? midOptionsWithoutGids[0]?.value || '' : '');

  const [processStep, setProcessStep] = useState<ProcessStep>(ProcessStep.One);
  const [formData, setFormData] = useState<LinkPaymentFormData>({
    mid: initialMid,
    sendMethod: LinkPaymentSendMethod.SMS,
    goodsName: '',
    amount: 0,
    moid: '',
    paymentLimitDate: moment().format('YYYY.MM.DD'),
    buyerName: '',
    email: '',
    phoneNumber: '',
    isIdentity: false,
    identityType: IdentityType.INDIVIDUAL,
    identityValue: '',
    language: Language.KR,
    linkContentType: LinkContentType.BASIC
  });

  useSetHeaderTitle('링크결제 신청');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);

  // Step1 필수 필드 검증
  const isStep1Valid = () => {
    return (
      formData.mid !== '' &&
      formData.sendMethod !== '' &&
      formData.goodsName.trim() !== '' &&
      formData.amount > 0 &&
      formData.moid.trim() !== '' &&
      formData.paymentLimitDate !== ''
    );
  };

  // 전화번호 형식 검증
  const isValidPhoneNumber = (phone: string) => {
    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);
  };

  // Step2 필수 필드 검증
  const isStep2Valid = () => {

    const basicFieldsValid = formData.sendMethod === 'EMAIL'
      ? formData.email.trim() !== '' && isValidEmail(formData.email)
      : formData.buyerName.trim() !== '' && formData.phoneNumber.trim() !== '' && isValidPhoneNumber(formData.phoneNumber);

    if (formData.isIdentity) {
      return basicFieldsValid && formData.identityValue.trim() !== '';
    }

    return basicFieldsValid;
  };

  const onClickToBack = () => {
    setProcessStep(ProcessStep.One);
  };

  const onClickToChangeTab = () => {
    if (processStep === ProcessStep.One) {
      setProcessStep(ProcessStep.Two);
    }
    else if (processStep === ProcessStep.Two) {
      navigate(PATHS.additionalService.linkPayment.requestConfirm, {
        state: { formData }
      });
    }
  };

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="option-list">
              <div className="issue-progress">
                <div className="bar">
                  {(processStep === ProcessStep.One) &&
                    <div
                      className="fill"
                      style={{ width: '50%' }}
                    ></div>
                  }
                  {(processStep === ProcessStep.Two) &&
                    <div
                      className="fill"
                      style={{ width: '100%' }}
                    ></div>
                  }
                </div>
              </div>

              {(processStep === ProcessStep.One) &&
                <LinkPaymentStep1
                  formData={formData}
                  setFormData={setFormData}
                ></LinkPaymentStep1>
              }
              {(processStep === ProcessStep.Two) &&
                <LinkPaymentStep2
                  setProcessStep={setProcessStep}
                  formData={formData}
                  setFormData={setFormData}
                ></LinkPaymentStep2>
              }

            </div>
            {(processStep === ProcessStep.One) &&
              <div className="apply-row">
                <button
                  className="btn-50 btn-blue flex-1"
                  onClick={() => onClickToChangeTab()}
                  disabled={!isStep1Valid()}
                >다음</button>
              </div>
            }
            {(processStep === ProcessStep.Two) &&
              <div className="apply-row two-button">
                <button
                  className="btn-50 btn-darkgray flex-1"
                  onClick={() => onClickToBack()}
                >이전</button>
                <button
                  className="btn-50 btn-blue flex-3"
                  onClick={() => onClickToChangeTab()}
                  disabled={!isStep2Valid()}
                >결제 신청</button>
              </div>
            }
          </div>
        </div>
      </main>

    </>
  );
};