import { Box, Button, FormControl, FormControlLabel, TextField, Tooltip } from '@mui/material';
import pick from 'lodash/pick';
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 { Icon } from '@iconify/react';
import DocumentIcon from '@iconify-icons/material-symbols/unknown-document-outline-rounded';
import { useNodeContext } from '../../../contexts/node';
import { useBlockletContext } from '../../../contexts/blocklet';
import SwitchControl from '../../component/switch-control';
import Section from '../../../component/section';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const defaultValue = {
  enabled: false,
  clientId: '',
  clientSecret: ''
};
function OAuthGoogle() {
  const {
    api
  } = useNodeContext();
  const {
    blocklet
  } = useBlockletContext();
  const {
    t,
    locale
  } = useLocaleContext();
  const did = blocklet?.meta?.did;
  const authData = Object.assign({
    ...defaultValue
  }, blocklet?.settings?.oauth?.google || {});
  const {
    handleSubmit,
    control,
    formState,
    watch,
    reset
  } = useForm({
    defaultValues: pick(authData, Object.keys(defaultValue))
  });
  const enabled = watch('enabled');
  const onSubmit = useMemoizedFn(async data => {
    try {
      const {
        blocklet: blockletChanged
      } = await api.configOAuth({
        input: {
          did,
          oauth: JSON.stringify({
            google: data
          })
        }
      });
      const defaultValues = Object.assign({
        ...defaultValue
      }, blockletChanged?.settings?.oauth?.google || {});
      // 将当前表单的默认值重置为新的数据，这样能够修正页面的 isDirty 数据
      reset(defaultValues);
      Toast.success(t('oauth.saveSuccess'));
    } catch (err) {
      Toast.error(err.message || t('oauth.saveFailed'));
    }
  });
  const validateClientId = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('oauth.google.clientIdDescription');
    }
    return true;
  });
  const validateClientSecret = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('oauth.google.clientSecretDescription');
    }
    return true;
  });
  const noop = useMemoizedFn(() => 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]);
  return /*#__PURE__*/_jsx(Box, {
    children: /*#__PURE__*/_jsxs("form", {
      onSubmit: handleSubmit(onSubmit),
      disabled: true,
      children: [/*#__PURE__*/_jsx(Section, {
        title: /*#__PURE__*/_jsxs(Box, {
          sx: {
            display: 'flex',
            alignItems: 'center',
            gap: 1
          },
          children: [/*#__PURE__*/_jsx("span", {
            children: t('oauth.google.enable')
          }), /*#__PURE__*/_jsx(Tooltip, {
            title: t('oauth.viewDocument'),
            children: /*#__PURE__*/_jsx(Box, {
              component: "a",
              sx: {
                display: 'inline-block',
                color: 'inherit',
                fontSize: 0,
                lineHeight: 1
              },
              href: documentUrl,
              target: "_blank",
              rel: "noreferrer",
              children: /*#__PURE__*/_jsx(Icon, {
                icon: DocumentIcon,
                fontSize: 20
              })
            })
          })]
        }),
        mb: 2.5,
        children: /*#__PURE__*/_jsx(Controller, {
          name: "enabled",
          control: control,
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControlLabel, {
            control: /*#__PURE__*/_jsx(SwitchControl, {
              sx: {
                ml: 1
              },
              checked: field.value,
              ...field
            })
          })
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('oauth.google.clientId'),
        children: /*#__PURE__*/_jsx(Controller, {
          name: "clientId",
          control: control,
          rules: {
            validate: enabled ? validateClientId : noop
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControl, {
            fullWidth: true,
            children: /*#__PURE__*/_jsx(TextField, {
              ...field,
              size: "small",
              label: t('oauth.google.clientId'),
              error: !!formState.errors[field.name],
              helperText: formState.errors[field.name]?.message || '　',
              disabled: !enabled
            })
          })
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('oauth.google.clientSecret'),
        children: /*#__PURE__*/_jsx(Controller, {
          name: "clientSecret",
          control: control,
          rules: {
            validate: enabled ? validateClientSecret : noop
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControl, {
            fullWidth: true,
            children: /*#__PURE__*/_jsx(TextField, {
              ...field,
              size: "small",
              type: "password",
              label: t('oauth.google.clientSecret'),
              error: !!formState.errors[field.name],
              helperText: formState.errors[field.name]?.message || '　',
              disabled: !enabled
            })
          })
        })
      }), /*#__PURE__*/_jsx(Button, {
        type: "submit",
        variant: "contained",
        onSubmit: handleSubmit(onSubmit),
        disabled: !formState.isDirty,
        children: t('oauth.save')
      })]
    })
  });
}
export default OAuthGoogle;