import { useMemoizedFn, useReactive } from 'ahooks';
import mailOutlineRoundedIcon from '@iconify-icons/material-symbols/mail-outline-rounded';
import { LOGIN_PROVIDER } from '@arcblock/ux/lib/Util/constant';
import { translate } from '@arcblock/ux/lib/Locale/util';

import EmailListItem from './list-item';
import EmailPlaceholder from './placeholder';
import defaultTranslations from '../../assets/locale';

export default function useEmailPlugin({ baseUrl }) {
  const state = useReactive({
    baseUrl,
    status: 'idle',
    get computedStatus() {
      if (this.status === 'idle') {
        return 'creating';
      }
      if (this.status === 'creating') {
        return 'scanned';
      }
      if (this.status === 'sending') {
        return 'scanned';
      }
      if (this.status === 'verifying') {
        return 'scanned';
      }
      return this.status;
    },
    error: '',
    magicToken: '',
    reset() {
      this.status = 'idle';
      this.error = '';
      this.magicToken = '';
    },
  });
  const name = LOGIN_PROVIDER.EMAIL;
  const title = 'Email';
  const icon = mailOutlineRoundedIcon;
  const translations = {
    zh: {
      ...defaultTranslations.zh,
      email: '邮箱地址',
      emailPlaceholder: '请输入邮箱地址',
      sendCode: '发送验证邮件',
      confirm: '确认',
      verifyEmail: '登录链接已发送至邮箱，请登录邮箱查看',
      useCode: '使用验证码',
      codePlaceholder: '请输入验证码',
      orUseCodePlaceholder: '或使用验证码',
      emailInvalid: '邮箱格式不正确',
      emailRequired: '邮箱地址不能为空',
    },
    en: {
      ...defaultTranslations.en,
      email: 'Email',
      emailPlaceholder: 'Enter your email address',
      sendCode: 'Send Verification Email',
      confirm: 'Confirm',
      verifyEmail: 'Login link sent! Please check your email.',
      useCode: 'Use Verification Code',
      codePlaceholder: 'Enter your verification code.',
      orUseCodePlaceholder: 'Or use verification code.',
      emailInvalid: 'Email format is incorrect',
      emailRequired: 'Email is required',
    },
  };
  const t = useMemoizedFn((key, data = {}, locale = 'en') => {
    return translate(translations, key, locale, 'en', data);
  });

  return {
    name,
    title,
    icon,
    renderListItem(props) {
      return <EmailListItem {...props} state={state} name={name} title={title} icon={icon} t={t} />;
    },
    renderPlaceholder(props) {
      return <EmailPlaceholder {...props} state={state} name={name} title={title} icon={icon} t={t} />;
    },
    order: 100,
    state,
  };
}
