/* eslint-disable react/no-array-index-key */
import React, { useState } 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 Box from '@mui/material/Box';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import IconButton from '@mui/material/IconButton';
import MenuItem from '@mui/material/MenuItem';
import TextField from '@mui/material/TextField';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Button from '@arcblock/ux/lib/Button';
import DeleteIcon from '@arcblock/icons/lib/DeleteIcon';
import Empty from '@arcblock/ux/lib/Empty';
import { ROLES } from '@abtnode/constant';
import Toast from '@arcblock/ux/lib/Toast';
import { useNodeContext } from '../../contexts/node';
import { useTeamContext } from '../../contexts/team';
import { sleep, formatError } from '../../util';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
var LongArrow = function LongArrow(props) {
  return /*#__PURE__*/_jsx("svg", {
    ...props,
    children: /*#__PURE__*/_jsx("path", {
      d: "M64.707 8.707a1 1 0 0 0 0-1.414L58.343.929a1 1 0 1 0-1.414 1.414L62.586 8l-5.657 5.657a1 1 0 0 0 1.414 1.414l6.364-6.364ZM0 9h64V7H0v2Z",
      fill: "#666"
    })
  });
};
LongArrow.defaultProps = {
  width: "65",
  height: "16",
  fill: "none",
  xmlns: "http://www.w3.org/2000/svg"
};
const canSave = (issuerDid, mappings) => {
  if (!issuerDid) {
    return false;
  }
  return !mappings.some(x => !x.from.passport || !x.to.role);
};
export default function TrustedIssuer({
  onCancel,
  onSuccess,
  data = {},
  trustedPassports = []
}) {
  const {
    api
  } = useNodeContext();
  const {
    roles,
    teamDid
  } = useTeamContext();
  const {
    t
  } = useLocaleContext();
  const [loading, setLoading] = useState(false);
  const [issuerDid, setIssuerDid] = useState(data.issuerDid || '');
  const [remark, setRemark] = useState(data.remark || '');
  const [mappings, setMappings] = useState(cloneDeep(data.mappings) || []);
  const editIndex = trustedPassports.findIndex(x => x.issuerDid === data.issuerDid);
  const configTrustedPassports = async () => {
    if (loading) {
      return;
    }
    const item = {
      issuerDid,
      remark,
      mappings: mappings.map(x => ({
        ...x,
        to: {
          ...x.to,
          ttl: x.to.ttl || 0
        }
      }))
    };
    const trustedList = [...trustedPassports];
    if (editIndex === -1) {
      trustedList.unshift(item);
    } else {
      trustedList[editIndex] = item;
    }
    try {
      setLoading(true);
      await api.configTrustedPassports({
        input: {
          teamDid,
          trustedPassports: trustedList
        }
      });
      await sleep(800);
      setLoading(false);
      Toast.success(t('common.saveSuccess'));
      onSuccess();
    } catch (err) {
      setLoading(false);
      Toast.error(formatError(err));
    }
  };
  return /*#__PURE__*/_jsx(Dialog, {
    title: t('team.passport.trustedIssuers'),
    open: true,
    showCloseButton: false,
    PaperProps: {
      style: {
        minHeight: '80vh'
      }
    },
    fullWidth: true,
    prepend: /*#__PURE__*/_jsx(IconButton, {
      onClick: onCancel,
      "data-cy": "trusted-issuer-close",
      size: "large",
      children: /*#__PURE__*/_jsx(ArrowBackIcon, {})
    }),
    actions: /*#__PURE__*/_jsxs(_Fragment, {
      children: [/*#__PURE__*/_jsx(Button, {
        onClick: onCancel,
        color: "inherit",
        children: t('common.cancel')
      }), /*#__PURE__*/_jsxs(Button, {
        onClick: () => configTrustedPassports(),
        color: "primary",
        disabled: !canSave(issuerDid, mappings) || !remark || loading,
        variant: "contained",
        autoFocus: true,
        "data-cy": "save-mapping",
        children: [loading && /*#__PURE__*/_jsx(Spinner, {
          size: 16
        }), t('common.save')]
      })]
    }),
    children: /*#__PURE__*/_jsx(Div, {
      children: /*#__PURE__*/_jsxs("div", {
        className: "dialog-content",
        children: [/*#__PURE__*/_jsx(TextField, {
          fullWidth: true,
          "data-cy": "input-issuer-did",
          placeholder: t('team.passport.issuerDid'),
          value: issuerDid,
          onChange: event => {
            setIssuerDid(event.target.value);
          }
        }), /*#__PURE__*/_jsx(TextField, {
          style: {
            marginTop: 16
          },
          fullWidth: true,
          "data-cy": "input-issuer-remark",
          placeholder: t('common.remark'),
          value: remark,
          onChange: event => {
            setRemark(event.target.value);
          }
        }), /*#__PURE__*/_jsxs(Box, {
          sx: {
            mt: '30px',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center'
          },
          children: [/*#__PURE__*/_jsx(Box, {
            className: "dialog-h1",
            children: t('team.passport.mappingRule')
          }), /*#__PURE__*/_jsx(Box, {
            children: /*#__PURE__*/_jsx(Button, {
              variant: "outlined",
              color: "primary",
              "data-cy": "add-mapping",
              onClick: () => {
                setMappings(d => {
                  const res = [...d];
                  res.unshift({
                    from: {
                      passport: ''
                    },
                    to: {
                      role: ROLES.GUEST
                    }
                  });
                  return res;
                });
              },
              children: t('team.add')
            })
          })]
        }), /*#__PURE__*/_jsxs(Box, {
          className: "list",
          sx: {
            mt: -0.5
          },
          children: [mappings.map((item, index) => /*#__PURE__*/_jsxs(Box, {
            className: "mapping-item",
            sx: {
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              my: 1
            },
            children: [/*#__PURE__*/_jsxs(Box, {
              sx: {
                display: 'flex',
                alignItems: 'center',
                flexGrow: 1
              },
              children: [/*#__PURE__*/_jsx(Box, {
                sx: {
                  flexGrow: 1,
                  flexBasis: 1
                },
                children: /*#__PURE__*/_jsx(TextField, {
                  fullWidth: true,
                  size: "small",
                  "data-cy": `input-${index}-from`,
                  placeholder: "Issuer\u2019s Passport Name/ID *",
                  value: item.from.passport,
                  onChange: event => {
                    const {
                      value
                    } = event.target;
                    setMappings(d => {
                      const res = [...d];
                      res[index].from.passport = value;
                      return res;
                    });
                  },
                  sx: {
                    '& .MuiInputBase-input::placeholder': {
                      fontSize: 14
                    },
                    '& .Mui-focused .MuiOutlinedInput-notchedOutline': {
                      borderColor: 'primary.main'
                    }
                  }
                })
              }), /*#__PURE__*/_jsx(Box, {
                sx: {
                  flexShrink: 0,
                  mx: 1,
                  width: 65,
                  height: 16
                },
                children: /*#__PURE__*/_jsx(LongArrow, {})
              }), /*#__PURE__*/_jsx(Box, {
                sx: {
                  flexGrow: 1,
                  flexBasis: 1
                },
                children: /*#__PURE__*/_jsx(TextField, {
                  fullWidth: true,
                  size: "small",
                  select: true,
                  value: item.to.role,
                  onChange: e => {
                    setMappings(d => {
                      const res = [...d];
                      res[index].to.role = e.target.value;
                      return res;
                    });
                  },
                  variant: "outlined",
                  children: roles.filter(d => d.name !== 'owner').map(r => /*#__PURE__*/_jsx(MenuItem, {
                    value: r.name,
                    "data-cy": `passport-mapping-select-option-${r.name}`,
                    children: /*#__PURE__*/_jsx("span", {
                      children: r.title || r.name
                    })
                  }, r.name))
                })
              })]
            }), /*#__PURE__*/_jsx(Box, {
              sx: {
                flexShrink: 0
              },
              children: /*#__PURE__*/_jsx(IconButton, {
                onClick: () => {
                  setMappings(d => {
                    const res = [...d];
                    res.splice(index, 1);
                    return res;
                  });
                },
                size: "large",
                children: /*#__PURE__*/_jsx(DeleteIcon, {})
              })
            })]
          }, `mapping-${index}`)), !mappings.length && /*#__PURE__*/_jsx(Box, {
            sx: {
              my: 2,
              color: 'text.secondary',
              fontSize: '16px'
            },
            children: /*#__PURE__*/_jsx(Empty, {
              children: t('common.empty')
            })
          })]
        })]
      })
    })
  });
}
TrustedIssuer.propTypes = {
  onCancel: PropTypes.func.isRequired,
  onSuccess: PropTypes.func.isRequired,
  trustedPassports: PropTypes.array,
  data: PropTypes.object
};
const Div = styled.div`
  .dialog-h1 {
    font-size: 18px;
  }

  .list {
    .MuiIconButton-root {
      svg {
        fill: #bfbfbf;
      }
    }
  }
`;