import { Box, FormControl, TextField } from '@mui/material';
import pick from 'lodash/pick';
import noop from 'lodash/noop';
import { useCreation, useMemoizedFn } from 'ahooks';
import { Controller, useForm } from 'react-hook-form';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { CopyButton } from '@arcblock/ux/lib/ClickToCopy';
import { Icon } from '@iconify/react';
import externalLinkIcon from '@iconify-icons/tabler/external-link';
import { joinURL } from 'ufo';
import { WELLKNOWN_SERVICE_PATH_PREFIX } from '@abtnode/constant';
import { useImperativeHandle } from 'react';
import PropTypes from 'prop-types';
import { useNodeContext } from '../../../contexts/node';
import { useBlockletContext } from '../../../contexts/blocklet';
import Section from '../../../component/section';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const defaultValue = {
  clientId: '',
  clientSecret: ''
};
function OAuthGoogle({
  ref = null,
  onSuccess = noop,
  sortMaps = {}
}) {
  const {
    api
  } = useNodeContext();
  const {
    blocklet
  } = useBlockletContext();
  const {
    t,
    locale
  } = useLocaleContext();
  const did = blocklet?.meta?.did;
  const authData = Object.assign({
    ...defaultValue
  }, blocklet?.settings?.authentication?.google || {});
  const appUrl = (blocklet.environments || []).find(item => item.key === 'BLOCKLET_APP_URL')?.value || window.location.origin;
  const {
    handleSubmit,
    control,
    formState,
    reset
  } = useForm({
    defaultValues: pick(authData, Object.keys(defaultValue))
  });
  const onSubmit = useMemoizedFn(async data => {
    try {
      const {
        blocklet: blockletChanged
      } = await api.configAuthentication({
        input: {
          did,
          authentication: JSON.stringify({
            ...sortMaps,
            google: {
              ...data,
              order: sortMaps.google?.order ?? Object.keys(sortMaps).length,
              enabled: true,
              type: 'oauth'
            }
          })
        }
      });
      const defaultValues = Object.assign({
        ...defaultValue
      }, blockletChanged?.settings?.authentication?.google || {});
      // 将当前表单的默认值重置为新的数据，这样能够修正页面的 isDirty 数据
      reset(defaultValues);
      Toast.success(t('common.saveSuccess'));
      onSuccess();
    } catch (err) {
      Toast.error(err.message || t('common.saveFailed'));
    }
  });
  const validateClientId = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('authentication.google.clientIdDescription');
    }
    return true;
  });
  const validateClientSecret = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('authentication.google.clientSecretDescription');
    }
    return true;
  });
  const documentUrl = useCreation(() => {
    if (locale === 'zh') {
      return 'https://www.arcblock.io/blog/docs/did-connect/zh/oauth-config-google';
    }
    return 'https://www.arcblock.io/blog/docs/did-connect/en/oauth-config-google';
  }, [locale]);
  const callbackUrl = joinURL(appUrl, WELLKNOWN_SERVICE_PATH_PREFIX, 'oauth/callback/google');
  useImperativeHandle(ref, () => ({
    submit: handleSubmit(onSubmit)
  }), [handleSubmit, onSubmit]);
  return /*#__PURE__*/_jsx(Box, {
    children: /*#__PURE__*/_jsxs("form", {
      onSubmit: handleSubmit(onSubmit),
      disabled: true,
      children: [/*#__PURE__*/_jsx(Section, {
        title: t('authentication.viewDocument'),
        children: /*#__PURE__*/_jsxs(Box, {
          component: "a",
          href: documentUrl,
          target: "_blank",
          rel: "noopener noreferrer",
          sx: {
            verticalAlign: 'middle',
            color: 'inherit',
            fontSize: '14px',
            '&:hover': {
              textDecoration: 'underline'
            }
          },
          children: [documentUrl, /*#__PURE__*/_jsx(Box, {
            component: Icon,
            icon: externalLinkIcon,
            sx: {
              marginLeft: '6px',
              verticalAlign: 'middle',
              lineHeight: 1,
              scale: 1.1
            }
          })]
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('authentication.oauthCallbackUrl'),
        children: /*#__PURE__*/_jsxs(Box, {
          sx: {
            mb: 1,
            verticalAlign: 'middle',
            fontSize: '14px',
            wordBreak: 'break-all'
          },
          children: [callbackUrl, /*#__PURE__*/_jsx(CopyButton, {
            locale: locale,
            content: callbackUrl,
            style: {
              marginLeft: '6px',
              verticalAlign: 'middle',
              scale: 0.8,
              lineHeight: 1
            }
          })]
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('authentication.google.clientId'),
        children: /*#__PURE__*/_jsx(Controller, {
          name: "clientId",
          control: control,
          rules: {
            validate: validateClientId
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControl, {
            fullWidth: true,
            children: /*#__PURE__*/_jsx(TextField, {
              ...field,
              size: "small",
              label: t('authentication.google.clientId'),
              error: !!formState.errors[field.name],
              helperText: formState.errors[field.name]?.message || '　'
            })
          })
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('authentication.google.clientSecret'),
        children: /*#__PURE__*/_jsx(Controller, {
          name: "clientSecret",
          control: control,
          rules: {
            validate: validateClientSecret
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControl, {
            fullWidth: true,
            children: /*#__PURE__*/_jsx(TextField, {
              ...field,
              size: "small",
              type: "password",
              label: t('authentication.google.clientSecret'),
              error: !!formState.errors[field.name],
              helperText: formState.errors[field.name]?.message || '　'
            })
          })
        })
      })]
    })
  });
}
OAuthGoogle.propTypes = {
  ref: PropTypes.any,
  onSuccess: PropTypes.func,
  sortMaps: PropTypes.object
};
export default OAuthGoogle;