import PropTypes from 'prop-types';
import { useContext, useImperativeHandle } from 'react';
import { LocaleContext } from '@arcblock/ux/lib/Locale/context';
import { useMemoizedFn, useReactive } from 'ahooks';
import Button from '@arcblock/ux/lib/Button';
import Dialog from '@arcblock/ux/lib/Dialog';
import { Controller, useForm } from 'react-hook-form';
import { Checkbox, FormControl, FormControlLabel, FormGroup, FormHelperText, TextField } from '@mui/material';
import { useTheme } from '@arcblock/ux/lib/Theme';
import noop from 'lodash/noop';
import { useTeamContext } from '../../contexts/team';
import FormAccessRoleInput from './form-access-role-input';
import { convertAccessPolicyParams, formartAccessPolicyParams } from './utils';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
export default function BlockletAccessPolicyItemDialog({
  ref = null
}) {
  const {
    t
  } = useContext(LocaleContext);
  const {
    roles: roleList
  } = useTeamContext();
  const theme = useTheme();
  const leavingScreen = theme?.transitions?.duration?.leavingScreen || 300;
  const currentState = useReactive({
    mode: 'add',
    // add | edit | view
    show: false,
    callback: noop,
    get dialogTitle() {
      // eslint-disable-next-line react/no-this-in-sfc
      if (this.mode === 'edit') {
        return t('accessPolicy.edit');
      }
      // eslint-disable-next-line react/no-this-in-sfc
      if (this.mode === 'view') {
        return t('accessPolicy.view');
      }
      return t('accessPolicy.add');
    }
  });
  const {
    handleSubmit,
    control,
    watch,
    setValue,
    reset: resetForm,
    formState: {
      errors
    }
  } = useForm({
    mode: 'onChange',
    defaultValues: {
      name: '',
      description: '',
      roles: null,
      whoCanAccess: 'all'
    }
  });
  const reset = useMemoizedFn(() => {
    resetForm();
    currentState.mode = 'add';
  }, []);
  const close = useMemoizedFn(() => {
    currentState.show = false;
    setTimeout(() => {
      reset();
    }, leavingScreen);
  }, []);
  const open = useMemoizedFn((fn = noop, rawData = null) => {
    currentState.callback = fn;
    currentState.show = true;
    if (rawData) {
      if (rawData.id) {
        currentState.mode = 'edit';
      } else {
        currentState.mode = 'view';
      }
      const formatData = formartAccessPolicyParams(rawData);
      setValue('name', formatData.name);
      setValue('description', formatData.description);
      setValue('roles', formatData.roles);
      setValue('whoCanAccess', formatData.whoCanAccess);
    }
  }, []);
  useImperativeHandle(ref, () => ({
    open,
    close
  }), [open, close]);
  const handleFormSubmit = useMemoizedFn(params => {
    currentState.callback(convertAccessPolicyParams(params), close);
  }, []);
  const validateName = useMemoizedFn(raw => {
    const value = raw?.trim();
    if (!value) return t('common.requiredErrorText', {
      name: t('accessPolicy.form.name')
    });
    return true;
  });
  const whoCanAccess = watch('whoCanAccess');
  const isReadOnly = currentState.mode === 'view';
  const validateRoles = useMemoizedFn(raw => {
    if (['roles', 'roles_reverse'].includes(whoCanAccess)) {
      if (!raw || raw?.length === 0) {
        return t('common.requiredErrorText', {
          name: t('accessPolicy.form.roles')
        });
      }
    }
    return true;
  });
  const validateWhoCanAccess = useMemoizedFn(raw => {
    const value = raw?.trim();
    if (!value) return t('common.requiredErrorText', {
      name: t('accessPolicy.form.accessType')
    });
    return true;
  });
  return /*#__PURE__*/_jsx(Dialog, {
    open: currentState.show,
    title: currentState.dialogTitle,
    onClose: close,
    PaperProps: {
      style: {
        minHeight: 'unset'
      }
    },
    actions: /*#__PURE__*/_jsx(Button, {
      color: "primary",
      autoFocus: true,
      variant: "contained",
      onClick: handleSubmit(handleFormSubmit),
      children: t('common.confirm')
    }),
    children: /*#__PURE__*/_jsxs("form", {
      noValidate: true,
      autoComplete: "off",
      children: [/*#__PURE__*/_jsx(Controller, {
        name: "name",
        control: control,
        rules: {
          validate: validateName
        },
        render: ({
          field
        }) => {
          return /*#__PURE__*/_jsx(TextField, {
            fullWidth: true,
            required: true,
            margin: "dense",
            size: "small",
            disabled: isReadOnly,
            placeholder: t('accessPolicy.form.namePlaceholder'),
            label: t('accessPolicy.form.name'),
            error: !!errors?.name?.message,
            helperText: errors?.name?.message || ' ',
            ...field
          });
        }
      }), /*#__PURE__*/_jsx(Controller, {
        name: "whoCanAccess",
        control: control,
        rules: {
          validate: validateWhoCanAccess
        },
        render: ({
          field
        }) => {
          return /*#__PURE__*/_jsx(FormAccessRoleInput, {
            required: true,
            size: "small",
            margin: "dense",
            disabled: isReadOnly,
            error: !!errors?.whoCanAccess?.message,
            helperText: errors?.whoCanAccess?.message || ' ',
            ...field
          });
        }
      }), ['roles', 'roles_reverse'].includes(whoCanAccess) ? /*#__PURE__*/_jsx(Controller, {
        name: "roles",
        rules: {
          validate: validateRoles
        },
        control: control,
        render: ({
          field
        }) => {
          return /*#__PURE__*/_jsxs(FormControl, {
            variant: "standard",
            error: !!errors?.roles?.message,
            children: [/*#__PURE__*/_jsx(FormGroup, {
              sx: {
                display: 'flex',
                flexDirection: 'row',
                mt: -3
              },
              children: roleList.map(item => {
                return /*#__PURE__*/_jsx(FormControlLabel, {
                  control: /*#__PURE__*/_jsx(Checkbox, {
                    disabled: isReadOnly,
                    size: "small",
                    checked: field.value?.includes(item.name),
                    sx: {
                      p: 0.75
                    },
                    onChange: (e, val) => {
                      const rawValue = field.value || [];
                      if (val) {
                        field.onChange([...rawValue, item.name]);
                      } else {
                        field.onChange(rawValue.filter(x => x !== item.name));
                      }
                    }
                  }),
                  label: item.title
                }, item.name);
              })
            }), /*#__PURE__*/_jsx(FormHelperText, {
              sx: {
                transform: 'translateY(-8px)'
              },
              children: errors?.roles?.message || ' '
            })]
          });
        }
      }) : null, /*#__PURE__*/_jsx(Controller, {
        name: "description",
        control: control,
        render: ({
          field
        }) => {
          return /*#__PURE__*/_jsx(TextField, {
            fullWidth: true,
            multiline: true,
            disabled: isReadOnly,
            minRows: 3,
            maxRows: 7,
            margin: "dense",
            size: "small",
            placeholder: t('accessPolicy.form.descriptionPlaceholder'),
            label: t('accessPolicy.form.description'),
            helperText: errors?.message,
            ...field
          });
        }
      })]
    })
  });
}
BlockletAccessPolicyItemDialog.propTypes = {
  ref: PropTypes.any
};