import { useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';
import cloneDeep from 'lodash/cloneDeep';
import Dialog from '@arcblock/ux/lib/Dialog';
import Spinner from '@mui/material/CircularProgress';
import IconButton from '@mui/material/IconButton';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Button from '@arcblock/ux/lib/Button';
import EditIcon from '@arcblock/icons/lib/EditIcon';
import DeleteIcon from '@arcblock/icons/lib/DeleteIcon';
import Toast from '@arcblock/ux/lib/Toast';
import { useNodeContext } from '../../contexts/node';
import { useTeamContext } from '../../contexts/team';
import { formatError, isProtectedRole, BlockletAdminRoles } from '../../util';
import { withPermission } from '../../permission';
import Confirm from '../../confirm';
import MutateRole from './mutate-role';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
function PassportDetail({
  onCancel,
  onSuccess,
  onDelete,
  roleName,
  roles = undefined,
  hasPermission = false,
  orgId = ''
}) {
  const {
    api
  } = useNodeContext();
  const {
    roles: teamRoles,
    permissions,
    teamDid,
    refresh: refreshTeam,
    isNodeTeam
  } = useTeamContext();
  const {
    t
  } = useLocaleContext();
  const [binds, setBinds] = useState([]);
  const [updateForm, setUpdateForm] = useState(false);
  const [delConfirm, setDelConfirm] = useState(null);
  const [loading, setLoading] = useState(false);
  const allRoles = useMemo(() => {
    return roles || teamRoles;
  }, [roles, teamRoles]);
  const role = cloneDeep(allRoles.find(x => x.name === roleName));
  const isProtected = isProtectedRole(roleName);
  const deletePassport = async name => {
    if (loading) return;
    try {
      setLoading(true);
      await api.deleteRole({
        input: {
          teamDid,
          name
        }
      });
      onDelete();
    } catch (err) {
      Toast.error(err.message);
    } finally {
      setLoading(false);
      setDelConfirm(null);
    }
  };
  const getData = async (team, name) => {
    const res = await api.getPermissionsByRole({
      input: {
        teamDid: team,
        role: {
          name
        }
      }
    });
    const permissionList = res.permissions || [];
    const bindList = permissions.map(x => ({
      ...x,
      bind: permissionList.some(y => y.name === x.name)
    }));
    setBinds(bindList);
  };
  const onBind = async () => {
    setLoading(true);
    const grantNames = binds.filter(x => x.bind).map(x => x.name);
    try {
      await api.updatePermissionsForRole({
        input: {
          teamDid,
          roleName: role.name,
          grantNames
        }
      });
      Toast.success(t('common.saveSuccess'));
      onSuccess();
    } catch (err) {
      Toast.error(formatError(err));
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    if (teamDid && roleName) {
      getData(teamDid, roleName);
    }
  }, [teamDid, roleName]); // eslint-disable-line

  const readPermissionsOnly = isNodeTeam || !hasPermission;
  let bindPermission = null;
  if (isNodeTeam) {
    bindPermission = /*#__PURE__*/_jsxs("div", {
      className: "bind",
      children: [/*#__PURE__*/_jsx("div", {
        className: "title",
        children: t('common.permission')
      }), /*#__PURE__*/_jsx("div", {
        className: "list",
        children: binds
        // if readonly, show obtained permissions only
        .filter(x => readPermissionsOnly ? x.bind : true).map(x => /*#__PURE__*/_jsx("div", {
          className: "item",
          children: /*#__PURE__*/_jsx(FormControlLabel, {
            control: /*#__PURE__*/_jsx(Checkbox, {
              disabled: readPermissionsOnly,
              checked: x.bind,
              onChange: () => {
                setBinds(state => state.map(y => {
                  if (y.name === x.name) {
                    y.bind = !y.bind;
                  }
                  return y;
                }));
              },
              name: x.name
            }),
            label: x.description
          })
        }))
      })]
    });
  }
  return /*#__PURE__*/_jsxs(Dialog, {
    title: t('common.passport'),
    onClose: onCancel,
    open: true,
    fullWidth: true,
    toolbar: hasPermission && !isProtected && /*#__PURE__*/_jsxs(_Fragment, {
      children: [/*#__PURE__*/_jsx(IconButton, {
        onClick: () => setUpdateForm(role),
        "data-cy": `edit-passport-${role.name}`,
        size: "large",
        children: /*#__PURE__*/_jsx(EditIcon, {
          fill: "#bfbfbf"
        })
      }), /*#__PURE__*/_jsx(IconButton, {
        onClick: () => setDelConfirm({
          title: t('team.passport.delete.title'),
          description: t('team.passport.delete.description', {
            name: role.title
          }),
          confirm: t('common.delConfirm'),
          cancel: t('common.cancel'),
          onConfirm: () => {
            deletePassport(role.name);
          },
          onCancel: () => {
            setLoading(false);
            setDelConfirm(null);
          }
        }),
        "data-cy": `delete-passport-${role.name}`,
        size: "large",
        children: /*#__PURE__*/_jsx(DeleteIcon, {
          "data-cy": "close-passport-dialog",
          fill: "#bfbfbf"
        })
      })]
    }),
    actions: isNodeTeam && !readPermissionsOnly && /*#__PURE__*/_jsxs(_Fragment, {
      children: [/*#__PURE__*/_jsx(Button, {
        onClick: onCancel,
        color: "inherit",
        children: t('common.cancel')
      }), /*#__PURE__*/_jsxs(Button, {
        onClick: onBind,
        color: "primary",
        disabled: loading || !role,
        variant: "contained",
        autoFocus: true,
        "data-cy": "bind-permission-btn-confirm",
        children: [loading && /*#__PURE__*/_jsx(Spinner, {
          size: 16
        }), t('common.save')]
      })]
    }),
    children: [/*#__PURE__*/_jsxs(Div, {
      children: [!role && /*#__PURE__*/_jsx(Center, {
        children: /*#__PURE__*/_jsx(Spinner, {})
      }), role && /*#__PURE__*/_jsxs("div", {
        className: "dialog-content",
        children: [/*#__PURE__*/_jsxs("div", {
          className: "header",
          children: [/*#__PURE__*/_jsx("div", {
            className: "title",
            children: role.title
          }), /*#__PURE__*/_jsx("div", {
            className: "description",
            style: {
              marginTop: isNodeTeam ? 16 : 48
            },
            children: role.description
          })]
        }), bindPermission]
      })]
    }), updateForm && /*#__PURE__*/_jsx(MutateRole, {
      teamDid: teamDid,
      onCancel: () => setUpdateForm(null),
      onSuccess: () => {
        setUpdateForm(null);
        if (orgId) {
          onSuccess();
        } else {
          refreshTeam();
        }
      },
      mode: "update",
      roleName: updateForm.name,
      item: updateForm,
      orgId: orgId
    }), delConfirm && /*#__PURE__*/_jsx(Confirm, {
      title: delConfirm.title,
      description: delConfirm.description,
      confirm: delConfirm.confirm,
      cancel: delConfirm.cancel,
      params: delConfirm.params,
      onConfirm: delConfirm.onConfirm,
      onCancel: delConfirm.onCancel
    })]
  });
}
const PassportDetailInDaemon = withPermission(PassportDetail, 'mutate_team');
const PassportDetailInService = withPermission(PassportDetail, '', BlockletAdminRoles);
export default function PassportDetailWithPermission(props) {
  const {
    inService
  } = useNodeContext();
  if (inService) {
    return /*#__PURE__*/_jsx(PassportDetailInService, {
      ...props
    });
  }
  return /*#__PURE__*/_jsx(PassportDetailInDaemon, {
    ...props
  });
}
export { PassportDetail };
PassportDetail.propTypes = {
  roleName: PropTypes.string.isRequired,
  onCancel: PropTypes.func.isRequired,
  onSuccess: PropTypes.func.isRequired,
  onDelete: PropTypes.func.isRequired,
  hasPermission: PropTypes.bool,
  roles: PropTypes.array,
  orgId: PropTypes.string
};
const Div = styled.div`
  .header {
    .title {
      font-weight: 400;
      font-size: 24px;
      line-height: 28px;
      color: ${({
  theme
}) => theme.palette.text.primary};
    }

    .description {
      margin-top: 16px;
      font-weight: 400;
      font-size: 16px;
      line-height: 19px;
      color: ${({
  theme
}) => theme.palette.text.secondary};
    }
  }

  .bind {
    margin-top: 24px;
    .title {
      font-weight: 400;
      font-size: 16px;
      line-height: 19px;
      color: ${({
  theme
}) => theme.palette.text.secondary};
      margin-bottom: 24px;
    }
    .item {
      margin-top: 24px;
    }

    .MuiFormControlLabel-label {
      font-weight: 400;
      font-size: 16px;
      line-height: 19px;
      color: ${({
  theme
}) => theme.palette.text.secondary};
    }

    .PrivateSwitchBase-root-45 {
      padding: 0;
      padding-right: 12px;
    }
  }
`;
const Center = styled.div`
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
`;