import { Box, Button, FormControl, FormControlLabel, TextField } from '@mui/material';
import pick from 'lodash/pick';
import { 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 { 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 OAuthTwitter() {
  const {
    api
  } = useNodeContext();
  const {
    blocklet
  } = useBlockletContext();
  const {
    t
  } = useLocaleContext();
  const did = blocklet?.meta?.did;
  const twitter = Object.assign({
    ...defaultValue
  }, blocklet?.settings?.oauth?.twitter || {});
  const {
    handleSubmit,
    control,
    formState,
    watch,
    reset
  } = useForm({
    defaultValues: pick(twitter, Object.keys(defaultValue))
  });
  const enabled = watch('enabled');
  const onSubmit = useMemoizedFn(async data => {
    try {
      const {
        blocklet: blockletChanged
      } = await api.configOAuth({
        input: {
          did,
          oauth: JSON.stringify({
            twitter: data
          })
        }
      });
      const defaultValues = Object.assign({
        ...defaultValue
      }, blockletChanged?.settings?.oauth?.twitter || {});
      // 将当前表单的默认值重置为新的数据，这样能够修正页面的 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.twitter.clientIdDescription');
    }
    return true;
  });
  const validateClientSecret = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('oauth.twitter.clientSecretDescription');
    }
    return true;
  });
  const noop = useMemoizedFn(() => true);
  return /*#__PURE__*/_jsx(Box, {
    children: /*#__PURE__*/_jsxs("form", {
      onSubmit: handleSubmit(onSubmit),
      disabled: true,
      children: [/*#__PURE__*/_jsx(Section, {
        title: /*#__PURE__*/_jsx(Box, {
          sx: {
            display: 'flex',
            alignItems: 'center',
            gap: 1
          },
          children: /*#__PURE__*/_jsx("span", {
            children: t('oauth.twitter.enable')
          })
        }),
        mb: 2.5,
        sx: {
          '& .section-content': {
            alignItems: 'center'
          }
        },
        children: /*#__PURE__*/_jsx(Controller, {
          name: "enabled",
          control: control,
          sx: {
            alignItems: 'center'
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControlLabel, {
            control: /*#__PURE__*/_jsx(SwitchControl, {
              sx: {
                ml: 1
              },
              size: "small",
              checked: field.value,
              ...field
            })
          })
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('oauth.twitter.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.twitter.clientId'),
              error: !!formState.errors[field.name],
              helperText: formState.errors[field.name]?.message || '　',
              disabled: !enabled
            })
          })
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('oauth.twitter.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.twitter.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 OAuthTwitter;