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,
  teamId: '',
  serviceId: '',
  keyId: '',
  authKey: '',
  bundleId: ''
};
function OAuthApple() {
  const {
    api
  } = useNodeContext();
  const {
    blocklet
  } = useBlockletContext();
  const {
    t
  } = useLocaleContext();
  const did = blocklet?.meta?.did;
  const authData = Object.assign({
    ...defaultValue
  }, blocklet?.settings?.oauth?.apple || {});
  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({
            apple: data
          })
        }
      });
      const defaultValues = Object.assign({
        ...defaultValue
      }, blockletChanged?.settings?.oauth?.apple || {});
      // 将当前表单的默认值重置为新的数据，这样能够修正页面的 isDirty 数据
      reset(defaultValues);
      Toast.success(t('oauth.saveSuccess'));
    } catch (err) {
      Toast.error(err.message || t('oauth.saveFailed'));
    }
  });
  const validateTeamId = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('oauth.apple.teamIdDescription');
    }
    return true;
  });
  const validateServiceId = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('oauth.apple.serviceIdDescription');
    }
    return true;
  });
  const validateKeyId = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('oauth.apple.keyIdDescription');
    }
    return true;
  });
  const validateAuthKey = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('oauth.apple.authKeyDescription');
    }
    return true;
  });
  const validateBundleId = useMemoizedFn(val => {
    if (!val?.trim()) {
      return t('oauth.apple.bundleIdDescription');
    }
    return true;
  });
  const noop = useMemoizedFn(() => true);
  return /*#__PURE__*/_jsx(Box, {
    children: /*#__PURE__*/_jsxs("form", {
      onSubmit: handleSubmit(onSubmit),
      disabled: true,
      children: [/*#__PURE__*/_jsx(Section, {
        title: t('oauth.apple.enable'),
        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.apple.teamId'),
        children: /*#__PURE__*/_jsx(Controller, {
          name: "teamId",
          control: control,
          rules: {
            validate: enabled ? validateTeamId : noop
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControl, {
            fullWidth: true,
            children: /*#__PURE__*/_jsx(TextField, {
              ...field,
              size: "small",
              label: t('oauth.apple.teamId'),
              error: !!formState.errors[field.name],
              helperText: formState.errors[field.name]?.message || '　',
              disabled: !enabled
            })
          })
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('oauth.apple.bundleId'),
        children: /*#__PURE__*/_jsx(Controller, {
          name: "bundleId",
          control: control,
          rules: {
            validate: enabled ? validateBundleId : noop
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControl, {
            fullWidth: true,
            children: /*#__PURE__*/_jsx(TextField, {
              ...field,
              size: "small",
              label: t('oauth.apple.bundleId'),
              error: !!formState.errors[field.name],
              helperText: formState.errors[field.name]?.message || '　',
              disabled: !enabled
            })
          })
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('oauth.apple.serviceId'),
        children: /*#__PURE__*/_jsx(Controller, {
          name: "serviceId",
          control: control,
          rules: {
            validate: enabled ? validateServiceId : noop
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControl, {
            fullWidth: true,
            children: /*#__PURE__*/_jsx(TextField, {
              ...field,
              size: "small",
              label: t('oauth.apple.serviceId'),
              error: !!formState.errors[field.name],
              helperText: formState.errors[field.name]?.message || '　',
              disabled: !enabled
            })
          })
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('oauth.apple.keyId'),
        children: /*#__PURE__*/_jsx(Controller, {
          name: "keyId",
          control: control,
          rules: {
            validate: enabled ? validateKeyId : noop
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControl, {
            fullWidth: true,
            children: /*#__PURE__*/_jsx(TextField, {
              ...field,
              size: "small",
              label: t('oauth.apple.keyId'),
              error: !!formState.errors[field.name],
              helperText: formState.errors[field.name]?.message || '　',
              disabled: !enabled
            })
          })
        })
      }), /*#__PURE__*/_jsx(Section, {
        title: t('oauth.apple.authKey'),
        children: /*#__PURE__*/_jsx(Controller, {
          name: "authKey",
          control: control,
          rules: {
            validate: enabled ? validateAuthKey : noop
          },
          render: ({
            field
          }) => /*#__PURE__*/_jsx(FormControl, {
            fullWidth: true,
            children: /*#__PURE__*/_jsx(TextField, {
              ...field,
              size: "small",
              type: "password",
              label: t('oauth.apple.authKey'),
              multiline: true,
              rows: 4,
              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 OAuthApple;