import { BaseEventOrig, Button, ButtonProps, ITouchEvent } from '@tarojs/components';

import classNames from 'classnames';
import { useCallback } from 'react';

import { logWithPrefix } from '@/utils/common';
import Toast from '@/utils/toast';
import { requestUserInfo, setPhoneNumber } from '@/utils/user';

import './index.less';

export enum BindPhoneStatus {
  Success,
  Cancel,
  Error,
}

export interface IPhoneButtonProps extends ButtonProps {
  message?: string;
  // 绑定后是否需要刷新接口获取手机号
  needPhone?: boolean;
  onBindPhone?: (status: BindPhoneStatus) => void;
  onSuccess?: (e: ITouchEvent) => void;
}

const PREFIX = 'phone-button';
const log = logWithPrefix(PREFIX);

export default function PhoneButton(props: IPhoneButtonProps) {
  const {
    className,
    children,
    message = '绑定成功',
    openType,
    needPhone,
    onSuccess,
    onBindPhone,
    ...otherProps
  } = props;

  const handleGetPhoneNumber = useCallback(
    async (e: BaseEventOrig<ButtonProps.onGetPhoneNumberEventDetail>) => {
      log('handleGetPhoneNumber', e.detail.code, e.detail.iv, e.detail.encryptedData);
      const encryptedData = e.detail.encryptedData;
      const iv = e.detail.iv;
      if (!encryptedData || !iv) {
        onBindPhone?.(BindPhoneStatus.Cancel);
        return Toast.error('取消授权');
      }
      try {
        await setPhoneNumber({ encryptedData, iv });
        needPhone && (await requestUserInfo());
        Toast.success(message);
        onBindPhone?.(BindPhoneStatus.Success);
        onSuccess?.(e as ITouchEvent);
      } catch (err) {
        onBindPhone?.(BindPhoneStatus.Error);
        Toast.error('绑定失败');
        log('bind phone fail', err);
      }
    },
    [message, needPhone, onSuccess, onBindPhone]
  );

  return (
    <Button
      {...otherProps}
      className={classNames(PREFIX, className)}
      openType="getPhoneNumber"
      onGetPhoneNumber={handleGetPhoneNumber}
    >
      {children}
    </Button>
  );
}
