import PropTypes from 'prop-types';
import { Alert, Box, CircularProgress, DialogContentText, MenuItem, Select, TextField, InputLabel, FormControl, Typography } from '@mui/material';
import { useReactive } from 'ahooks';
import Dialog from '@arcblock/ux/lib/Dialog';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Button from '@arcblock/ux/lib/Button';
import DID from '@arcblock/ux/lib/DID';
import Avatar from '@arcblock/ux/lib/Avatar';
import copy from 'copy-to-clipboard';
import Toast from '@arcblock/ux/lib/Toast';
import dayjs from '@abtnode/util/lib/dayjs';
import ClickToCopy from '../../click-to-copy';
import { useNodeContext } from '../../contexts/node';
import { formatError, getInviteLink, formatToDatetime } from '../../util';
import TimeSelect from './time-select';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
export default function InviteMember({
  teamDid,
  roles = [],
  isFederated = false,
  apps = [],
  onCancel,
  onSuccess,
  onError = () => {},
  endpoint = ''
}) {
  const {
    api
  } = useNodeContext();
  const {
    t,
    locale
  } = useLocaleContext();
  const currentState = useReactive({
    loading: false,
    error: null,
    activeStep: 0,
    inviteInfo: null,
    role: '',
    remark: '',
    sourceAppPid: isFederated && apps.length > 0 ? apps[0].appPid : null,
    display: null,
    passportExpireTime: null,
    showPicker: false
  });
  const onCreate = async () => {
    if (!currentState.role) {
      currentState.error = t('team.member.error.passportEmpty');
      return;
    }
    if (currentState.passportExpireTime && dayjs(currentState.passportExpireTime).isBefore(dayjs())) {
      currentState.error = t('team.passport.customExpireTimeIsInvalid');
      return;
    }
    const trimRemark = currentState.remark.trim();
    currentState.error = null;
    currentState.loading = true;
    try {
      let sourceAppPid = currentState.sourceAppPid ?? null;
      if (sourceAppPid === teamDid) {
        sourceAppPid = null;
      }
      const args = {
        teamDid,
        role: currentState.role,
        remark: trimRemark,
        sourceAppPid,
        passportExpireTime: currentState.passportExpireTime ? currentState.passportExpireTime.toISOString() : ''
      };
      if (currentState.display) {
        args.display = {
          type: 'url',
          content: currentState.display
        };
      }
      const {
        inviteInfo
      } = await api.createMemberInvitation({
        input: args
      });
      currentState.inviteInfo = inviteInfo;
      currentState.activeStep = 1;
    } catch (err) {
      const errMsg = formatError(err);
      currentState.error = errMsg;
      onError(err);
    } finally {
      currentState.loading = false;
    }
  };
  const selectedRole = roles.find(r => r.name === currentState.role);
  const filteredRoles = roles.filter(r => r.name !== 'owner');
  const steps = [{
    body: /*#__PURE__*/_jsxs(Box, {
      sx: {
        display: 'flex',
        flexDirection: 'column',
        gap: 3
      },
      children: [apps.length > 1 ? /*#__PURE__*/_jsxs(FormControl, {
        fullWidth: true,
        children: [/*#__PURE__*/_jsx(InputLabel, {
          children: t('common.sourceApp')
        }), /*#__PURE__*/_jsx(Select, {
          value: currentState.sourceAppPid,
          onChange: e => {
            currentState.error = null;
            currentState.sourceAppPid = e.target.value;
          },
          fullWidth: true,
          label: t('common.passport'),
          disabled: currentState.loading,
          children: apps.map(r => /*#__PURE__*/_jsx(MenuItem, {
            value: r.appPid,
            children: /*#__PURE__*/_jsxs(Box, {
              sx: {
                display: 'flex',
                justifyContent: 'space-between',
                gap: 2,
                width: '100%'
              },
              children: [/*#__PURE__*/_jsxs(Box, {
                sx: {
                  display: 'flex',
                  alignItems: 'center',
                  gap: 1
                },
                children: [/*#__PURE__*/_jsx(Avatar, {
                  did: r.appPid,
                  size: 28
                }), r.appName]
              }), /*#__PURE__*/_jsx(DID, {
                did: r.appPid,
                compact: true,
                responsive: false
              })]
            })
          }, r.appPid))
        })]
      }) : null, /*#__PURE__*/_jsxs(FormControl, {
        fullWidth: true,
        variant: "outlined",
        children: [/*#__PURE__*/_jsx(InputLabel, {
          children: t('common.passport')
        }), /*#__PURE__*/_jsx(Select, {
          "data-cy": "invite-member-select-role",
          value: currentState.role,
          onChange: e => {
            currentState.error = null;
            currentState.role = e.target.value;
          },
          fullWidth: true,
          label: t('common.passport'),
          disabled: currentState.loading,
          onKeyPress: e => {
            if (e.key === 'Enter') {
              e.preventDefault();
              onCreate();
            }
          },
          children: filteredRoles.map(r => /*#__PURE__*/_jsx(MenuItem, {
            value: r.name,
            "data-cy": `invite-member-select-option-${r.name}`,
            children: /*#__PURE__*/_jsxs(Box, {
              sx: {
                display: 'flex',
                flexDirection: 'column'
              },
              children: [/*#__PURE__*/_jsx(Typography, {
                variant: "subtitle1",
                children: r.title || r.name
              }), /*#__PURE__*/_jsx(Typography, {
                variant: "caption",
                sx: {
                  opacity: 0.7
                },
                children: r.description
              })]
            })
          }, r.name))
        })]
      }), selectedRole?.extra?.display === 'custom' && /*#__PURE__*/_jsx(TextField, {
        label: t('common.display'),
        type: "url",
        value: currentState.display,
        onChange: e => {
          currentState.error = null;
          currentState.display = e.target.value;
        },
        fullWidth: true,
        variant: "outlined",
        margin: "normal"
      }), /*#__PURE__*/_jsx(TextField, {
        label: t('common.remark'),
        autoComplete: "off",
        variant: "outlined",
        fullWidth: true,
        value: currentState.remark,
        onChange: e => {
          currentState.error = null;
          currentState.remark = e.target.value;
        },
        disabled: currentState.loading,
        "data-cy": "invite-member-input-remark"
      }), /*#__PURE__*/_jsx(TimeSelect, {
        value: currentState.passportExpireTime,
        onChange: newValue => {
          currentState.error = null;
          currentState.passportExpireTime = newValue;
        },
        showError: false
      })]
    }),
    cancel: t('common.cancel'),
    confirm: t('team.member.inviteDialog.createInviteLink'),
    onCancel,
    onConfirm: onCreate
  }, {
    // eslint-disable-next-line react/no-unstable-nested-components
    body: () => {
      const link = getInviteLink({
        inviteId: currentState.inviteInfo?.inviteId,
        endpoint
      });
      return /*#__PURE__*/_jsxs("div", {
        children: [/*#__PURE__*/_jsx(Box, {
          sx: {
            fontSize: 16,
            fontWeight: 'bold'
          },
          children: t('team.member.inviteDialog.createSuccessTip', {
            expireDate: formatToDatetime(currentState.inviteInfo?.expireDate, locale)
          })
        }), /*#__PURE__*/_jsx("div", {
          style: {
            marginTop: '40px'
          }
        }), /*#__PURE__*/_jsx(ClickToCopy, {
          children: link
        })]
      });
    },
    confirm: t('common.copy'),
    onConfirm: () => {
      const link = getInviteLink({
        inviteId: currentState.inviteInfo?.inviteId,
        endpoint
      });
      if (process.env.NODE_ENV === 'e2e' || ['1', 'true'].includes(process.env.IS_E2E)) {
        onSuccess();
        return;
      }
      copy(link);
      Toast.success(t('common.copied'));
      onSuccess();
    },
    cancel: t('common.cancel'),
    onCancel
  }];
  const step = steps[currentState.activeStep];
  return /*#__PURE__*/_jsxs(Dialog, {
    title: t('common.invite'),
    fullWidth: true,
    open: true,
    showCloseButton: false,
    actions: /*#__PURE__*/_jsxs(_Fragment, {
      children: [step.cancel && /*#__PURE__*/_jsx(Button, {
        onClick: step.onCancel,
        color: "inherit",
        children: step.cancel
      }), /*#__PURE__*/_jsxs(Button, {
        onClick: step.onConfirm,
        color: "primary",
        disabled: currentState.loading || !currentState.role,
        variant: "contained",
        autoFocus: true,
        children: [currentState.loading && /*#__PURE__*/_jsx(CircularProgress, {
          size: 16
        }), step.confirm]
      })]
    }),
    children: [/*#__PURE__*/_jsx(DialogContentText, {
      component: "div",
      children: typeof step.body === 'function' ? step.body() : step.body
    }), !!currentState.error && /*#__PURE__*/_jsx(Alert, {
      severity: "error",
      sx: {
        mt: 2
      },
      children: currentState.error
    })]
  });
}
InviteMember.propTypes = {
  teamDid: PropTypes.string.isRequired,
  onCancel: PropTypes.func.isRequired,
  onSuccess: PropTypes.func.isRequired,
  onError: PropTypes.func,
  roles: PropTypes.array,
  apps: PropTypes.array,
  endpoint: PropTypes.string,
  isFederated: PropTypes.bool // 是否属于站点群应用
};