import { LoginType } from "@/entities/common/model/types";
import { IMAGE_ROOT } from "@/shared/constants/common";
import { useTranslation } from "react-i18next";
import { useAppBridge } from "@/hooks/useAppBridge";

export interface LoginTypeBottomSheetProps {
  loginTypeBottomSheetOn: boolean;
  setLoginTypeBottomSheetOn: (loginTypeBottomSheetOn: boolean) => void;
  loginType: LoginType;
  setLoginType: (loginType: string) => void;
  onBiometricRegistered?: () => void;
  isAndroid: boolean;
};

export const LoginTypeBottomSheet = ({
  setLoginTypeBottomSheetOn,
  loginType,
  setLoginType,
  onBiometricRegistered,
  isAndroid
}: LoginTypeBottomSheetProps) => {
  const { t } = useTranslation();
  const { registerBiometric, setLoginType: setLoginTypeNative } = useAppBridge();

  const onClickToClose = () => {
    setLoginTypeBottomSheetOn(false);
  };
  const onChangeLoginType = async (type: string) => {
    if (loginType !== type) {
      if (isAndroid) {
        setLoginTypeNative(type).then(() => {
            setLoginType(type);
            onClickToClose();
          }).catch(() => {
            onClickToClose();
          });
      } else {
        if (type === 'BIOMETRIC') {
          onClickToClose();
          registerBiometric().then(() => {
            onBiometricRegistered?.();
          }).catch(() => {
            // 에러 처리
          });
        } else {
          setLoginTypeNative(type).then(() => {
            setLoginType(type);
            onClickToClose();
          }).catch(() => {
            onClickToClose();
          });
        }
      }

    }
  };

  return (
    <>
      <div className="bg-dim"></div>
      <div className="bottomsheet">
        <div className="bottomsheet-header">
          <div className="bottomsheet-title">
            <h2>{t('settings.loginType.title')}</h2>
            <button
              className="close-btn"
              type="button"
            >
              <img
                src={IMAGE_ROOT + '/ico_close.svg'}
                alt={t('common.close')}
                onClick={onClickToClose}
              />
            </button>
          </div>
        </div>

        <div className="bottomsheet-content">
          <div className="bottom-section">
            <ul className="list-style-circle link">
              <li
                className={`${(loginType === LoginType.ID) ? 'selected' : ''}`}
                onClick={() => onChangeLoginType('ID')}
              >{t('settings.loginType.idPassword')}</li>
              <li
                className={`${(loginType === LoginType.BIOMETRIC) ? 'selected' : ''}`}
                onClick={() => onChangeLoginType('BIOMETRIC')}
              >{t('settings.loginType.biometric')}</li>
            </ul>
          </div>
        </div>
      </div>
    </>
  );
};