import { ChangeEvent, useState } from 'react';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { useQnaSaveMutation } from '@/entities/support/api/use-qna-save-mutation';
import { HeaderType } from '@/entities/common/model/types';
import { 
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useStore } from '@/shared/model/store';
import { useTranslation } from 'react-i18next';
import { PatternFormat } from 'react-number-format';
import { overlay } from 'overlay-kit';
import { Dialog } from '@/shared/ui/dialogs/dialog';
import { QnaSaveParams, QnaSaveResponse } from '@/entities/support/model/types';

export enum QnaRegisterPropsName {
  Mid = 'Mid',
  RequestType = 'RequestType',
  RequestName = 'RequestName',
  RequestTel = 'RequestTel',
  RequestEmail = 'RequestEmail',
  Title = 'Title',
  Contents = 'Contents',
};

export const QnaRegisterPage = () => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();
  const userMid = useStore.getState().UserStore.mid;

  const [mid, setMid] = useState<string>(userMid);
  const [requestType, setRequestType] = useState<string>('');
  const [requestName, setRequestName] = useState<string>('');
  const [requestTel, setRequestTel] = useState<string>('');
  const [requestEmail, setRequestEmail] = useState<string>('');
  const [title, setTitle] = useState<string>('');
  const [contents, setContents] = useState<string>('');

  useSetHeaderTitle(t('support.qna.title'));
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.support.qna.list);
  });

  const { mutateAsync: qnaSave } = useQnaSaveMutation();

  const setInputValue = (
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>,
    key: string
  ) => {
    let value = e.target.value;
    if(key === QnaRegisterPropsName.Mid){
      setMid(value);
    }
    else if(key === QnaRegisterPropsName.RequestType){
      setRequestType(value);
    }
    else if(key === QnaRegisterPropsName.RequestName){
      setRequestName(value);
    }
    else if(key === QnaRegisterPropsName.RequestTel){
      setRequestTel(value);
    }
    else if(key === QnaRegisterPropsName.RequestEmail){
      setRequestEmail(value);
    }
    else if(key === QnaRegisterPropsName.Title){
      setTitle(value);
    }
    else if(key === QnaRegisterPropsName.Contents){
      setContents(value);
    }
  };
  const showAlert = (msg: string) => {
    overlay.open(({
      isOpen,
      close,
      unmount
    }) => {
      return (
        <Dialog
          afterLeave={unmount}
          open={isOpen}
          onClose={close}
          message={ msg }
          buttonLabel={[t('support.qna.confirmButton')]}
        />
      );
    });
  }
  const checkEmail = (email: string) => {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    if(email != '' && email != 'undefined' && re.test(email)){
      return true;
    }
    else{
      return false;
    }
  };
  const callRegister = () => {
    if(!title){
      showAlert(t('support.qna.validation.title'));
      return;
    }
    else if(!requestType){
      showAlert(t('support.qna.validation.requestType'));
      return;
    }
    else if(!requestName){
      showAlert(t('support.qna.validation.requestName'));
      return;
    }
    else if(!requestTel){
      showAlert(t('support.qna.validation.requestTel'));
      return;
    }
    else if(requestEmail && !checkEmail(requestEmail)){
      showAlert(t('support.qna.validation.requestEmail'));
      return;
    }
    else if(!contents){
      showAlert(t('support.qna.validation.contents'));
      return;
    }
    let params: QnaSaveParams = {
      mid: mid,
      title: title,
      requestType: requestType,
      requestName: requestName,
      requestTel: requestTel,
      requestEmail: requestEmail,
      contents: contents,
    };
    qnaSave(params).then((rs: QnaSaveResponse) => {
      alert(t('support.qna.successMessage'));
      navigate(PATHS.support.qna.list);
    });
  };

  const onClickToRegisterQna = () => {
    callRegister();
  };

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane active">
            <div className="inq-form">
              <div className="inq-field">
                <div className="inq-label">
                  {t('support.qna.formLabels.title')} <span className="red">{t('support.qna.formLabels.required')}</span>
                </div>
                <div className="inq-control">
                  <input
                    type="text"
                    value={ title }
                    required= { true }
                    onChange={ (e: ChangeEvent<HTMLInputElement>) => setInputValue(e, QnaRegisterPropsName.Title) }
                  />
                </div>
              </div>
              <div className="inq-field">
                <div className="inq-label">
                  {t('support.qna.formLabels.inquiryType')} <span className="red">{t('support.qna.formLabels.required')}</span>
                </div>
                <div className="inq-control">
                  <select
                    value={ requestType }
                    required= { true }
                    onChange={ (e: ChangeEvent<HTMLSelectElement>) => setInputValue(e, QnaRegisterPropsName.RequestType) }
                  >
                    <option value="">{t('support.qna.categories.choose')}</option>
                    <option value="01">{t('support.qna.categories.01')}</option>
                    <option value="02">{t('support.qna.categories.02')}</option>
                    <option value="03">{t('support.qna.categories.03')}</option>
                    <option value="04">{t('support.qna.categories.04')}</option>
                    <option value="05">{t('support.qna.categories.05')}</option>
                    <option value="06">{t('support.qna.categories.06')}</option>
                    <option value="09">{t('support.qna.categories.09')}</option>
                  </select>
                </div>
              </div>
              <div className="inq-field">
                <div className="inq-label">
                  {t('support.qna.formLabels.requesterName')} <span className="red">{t('support.qna.formLabels.required')}</span>
                </div>
                <div className="inq-control">
                  <input
                    type="text"
                    value={ requestName }
                    required= { true }
                    onChange={ (e: ChangeEvent<HTMLInputElement>) => setInputValue(e, QnaRegisterPropsName.RequestName) }
                  />
                </div>
              </div>
              <div className="inq-field">
                <div className="inq-label">
                  {t('support.qna.formLabels.phoneNumber')} <span className="red">{t('support.qna.formLabels.required')}</span>
                </div>
                <div className="inq-control">
                  <PatternFormat
                    placeholder={t('support.qna.formLabels.phonePlaceholder')}
                    value={ requestTel }
                    valueIsNumericString
                    format="###########"
                    onChange={ (e: ChangeEvent<HTMLInputElement>) => setInputValue(e, QnaRegisterPropsName.RequestTel) }
                  ></PatternFormat>
                </div>
              </div>
              <div className="inq-field">
                <div className="inq-label">{t('support.qna.formLabels.emailAddress')}</div>
                <div className="inq-control">
                  <input
                    type="email"
                    placeholder={t('support.qna.formLabels.emailPlaceholder')}
                    value={ requestEmail }
                    onChange={ (e: ChangeEvent<HTMLInputElement>) => setInputValue(e, QnaRegisterPropsName.RequestEmail) }
                  />
                </div>
              </div>
              <div className="inq-text">
                <div className="inq-text-label">
                  {t('support.qna.formLabels.inquiryContents')} <span className="red">{t('support.qna.formLabels.required')}</span>
                </div>
                <div className="inq-text-body">
                  <textarea
                    value={ contents }
                    required= { true }
                    onChange={ (e: ChangeEvent<HTMLTextAreaElement>) => setInputValue(e, QnaRegisterPropsName.Contents) }
                  ></textarea>
                </div>
              </div>
            </div>
            <div className="apply-row">
              <button
                className="btn-50 btn-blue flex-1"
                onClick={ () => onClickToRegisterQna() }
              >{t('support.qna.submitButton')}</button>
            </div>
          </div>
        </div>
      </main>
    </>
  );
};