/* eslint-disable react/no-unstable-nested-components */
import React from 'react';
import PropTypes from 'prop-types';
import { Box, List, ListItem, ListItemAvatar, Skeleton, IconButton, useTheme, Chip, Button, Typography } from '@mui/material';
import { alpha } from '@mui/material/styles';
import DeleteIcon from '@mui/icons-material/Delete';
import UserCard from '@arcblock/ux/lib/UserCard';
import { CardType, InfoType } from '@arcblock/ux/lib/UserCard/types';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import RelativeTime from '@arcblock/ux/lib/RelativeTime';
import Datatable from '@arcblock/ux/lib/Datatable';
import { Icon } from '@iconify/react';
import { useOrgsContext } from '../context';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
function MemberSkeleton({
  index = 0
}) {
  const widthVariants = [{
    name: '75%',
    info: '45%',
    detail: '60%'
  }, {
    name: '65%',
    info: '55%',
    detail: '40%'
  }, {
    name: '90%',
    info: '30%',
    detail: '65%'
  }];
  const variant = widthVariants[index % widthVariants.length];
  return /*#__PURE__*/_jsxs(ListItem, {
    sx: {
      px: 0,
      py: 1
    },
    children: [/*#__PURE__*/_jsx(ListItemAvatar, {
      children: /*#__PURE__*/_jsx(Skeleton, {
        variant: "circular",
        width: 32,
        height: 32
      })
    }), /*#__PURE__*/_jsxs(Box, {
      sx: {
        flex: 1
      },
      children: [/*#__PURE__*/_jsx(Skeleton, {
        variant: "text",
        width: variant.name,
        height: 20,
        sx: {
          mb: 0.5
        }
      }), /*#__PURE__*/_jsx(Skeleton, {
        variant: "text",
        width: variant.info,
        height: 16,
        sx: {
          mb: 0.25
        }
      })]
    })]
  });
}
MemberSkeleton.propTypes = {
  index: PropTypes.number
};
export default function OrgMembers() {
  const {
    t,
    locale
  } = useLocaleContext();
  const {
    orgDetail,
    requests
  } = useOrgsContext();
  const {
    org,
    members,
    loading,
    editable,
    membersPaging: paging
  } = orgDetail || {};
  const theme = useTheme();
  const onTableChange = (tableState, action) => {
    if (action === 'changePage') {
      paging.page = tableState.page + 1;
      requests.getOrgMembers(org.id, paging);
    }
    if (action === 'changeRowsPerPage') {
      paging.page = 1;
      paging.pageSize = tableState.rowsPerPage;
      requests.getOrgMembers(org.id, paging);
    }
  };
  const columns = [{
    name: 'user',
    label: ' ',
    options: {
      filter: false,
      sort: false,
      setCellHeaderProps: () => ({
        style: {
          display: 'none'
        }
      }),
      setCellProps: () => ({
        style: {
          width: '33.33%'
        }
      }),
      customBodyRender: (value, tableMeta) => {
        const member = members[tableMeta.rowIndex];
        if (!member || !member.user) return null;
        const {
          user
        } = member;
        const isOwner = member.userDid === org.ownerDid;
        return /*#__PURE__*/_jsx(Box, {
          sx: {
            py: {
              xs: 0.5,
              sm: 1
            }
          },
          children: /*#__PURE__*/_jsx(UserCard, {
            avatarSize: 32,
            user: user,
            showDid: true,
            cardType: CardType.Detailed,
            infoType: InfoType.Minimal,
            sx: {
              border: 0,
              padding: 0
            },
            showHoverCard: false,
            renderTopRightContent: editable && !isOwner ? () => /*#__PURE__*/_jsx(Box, {
              sx: {
                display: {
                  xs: 'block',
                  sm: 'none'
                }
              },
              children: /*#__PURE__*/_jsx(IconButton, {
                size: "small",
                color: "error",
                "aria-label": "delete",
                title: t('team.orgs.invite.remove'),
                onClick: e => {
                  e.stopPropagation();
                  requests.removeOrgMember(org.id, member);
                },
                children: /*#__PURE__*/_jsx(DeleteIcon, {
                  fontSize: "small"
                })
              })
            }) : undefined
          })
        });
      }
    }
  }, {
    name: 'status',
    label: ' ',
    options: {
      filter: false,
      sort: false,
      setCellHeaderProps: () => ({
        style: {
          display: 'none'
        }
      }),
      setCellProps: () => ({
        style: {
          width: '33.33%'
        }
      }),
      customBodyRender: (value, tableMeta) => {
        const member = members[tableMeta.rowIndex];
        if (!member || !member.user) return null;
        const {
          user
        } = member;
        const {
          passports = []
        } = user;
        return /*#__PURE__*/_jsxs(Box, {
          sx: {
            display: 'flex',
            flexDirection: {
              xs: 'column',
              sm: 'row'
            },
            gap: 0.5,
            alignItems: 'flex-start',
            py: {
              xs: 0.5,
              sm: 1
            }
          },
          children: [/*#__PURE__*/_jsxs(Box, {
            sx: {
              display: {
                xs: 'flex',
                sm: 'none'
              },
              flexDirection: 'row',
              gap: 0.5,
              alignItems: 'center',
              flexWrap: 'nowrap',
              overflow: 'auto',
              maxWidth: '100%'
            },
            children: [passports.map(passport => /*#__PURE__*/_jsx(Chip, {
              label: passport.title,
              size: "small",
              sx: {
                flexShrink: 0
              }
            }, passport.id)), member.status === 'inviting' ? /*#__PURE__*/_jsx(Chip, {
              label: t('common.inviting'),
              size: "small",
              sx: {
                backgroundColor: alpha(theme.palette.warning.main, 0.15),
                color: theme.palette.warning.dark,
                flexShrink: 0
              }
            }) : /*#__PURE__*/_jsx(Chip, {
              label: t('team.orgs.active'),
              size: "small",
              sx: {
                backgroundColor: alpha(theme.palette.success.main, 0.15),
                color: theme.palette.success.dark,
                flexShrink: 0
              }
            }), member.updatedAt && /*#__PURE__*/_jsxs(Typography, {
              variant: "caption",
              color: "text.secondary",
              sx: {
                whiteSpace: 'nowrap',
                flexShrink: 0
              },
              children: [member.status === 'inviting' ? t('team.orgs.invitedAt') : t('team.orgs.joinedAt'), ' ', /*#__PURE__*/_jsx(RelativeTime, {
                value: member.updatedAt
              })]
            })]
          }), /*#__PURE__*/_jsxs(Box, {
            sx: {
              display: {
                xs: 'none',
                sm: 'flex'
              },
              flexDirection: 'row',
              gap: 0.5,
              alignItems: 'center'
            },
            children: [passports.map(passport => /*#__PURE__*/_jsx(Chip, {
              label: passport.title,
              size: "small"
            }, passport.id)), member.status === 'inviting' ? /*#__PURE__*/_jsx(Chip, {
              label: t('common.inviting'),
              size: "small",
              sx: {
                backgroundColor: alpha(theme.palette.warning.main, 0.15),
                color: theme.palette.warning.dark
              }
            }) : /*#__PURE__*/_jsx(Chip, {
              label: t('team.orgs.active'),
              size: "small",
              sx: {
                backgroundColor: alpha(theme.palette.success.main, 0.15),
                color: theme.palette.success.dark
              }
            })]
          })]
        });
      }
    }
  }, {
    name: 'updatedAt',
    label: ' ',
    options: {
      filter: false,
      sort: false,
      setCellHeaderProps: () => ({
        style: {
          display: 'none'
        }
      }),
      setCellProps: () => ({
        style: {
          width: '33.33%'
        }
      }),
      customBodyRender: (value, tableMeta) => {
        const member = members[tableMeta.rowIndex];
        if (!member || !member.updatedAt) return null;
        return /*#__PURE__*/_jsx(Box, {
          sx: {
            py: {
              xs: 0.5,
              sm: 1
            },
            display: {
              xs: 'none',
              sm: 'flex'
            },
            flexDirection: 'column',
            gap: 0.5,
            minWidth: 0
          },
          children: /*#__PURE__*/_jsxs(Typography, {
            variant: "caption",
            color: "text.secondary",
            sx: {
              whiteSpace: 'nowrap'
            },
            children: [member.status === 'inviting' ? t('team.orgs.invitedAt') : t('team.orgs.joinedAt'), /*#__PURE__*/_jsx(RelativeTime, {
              value: member.updatedAt
            })]
          })
        });
      }
    }
  }, {
    name: 'actions',
    label: ' ',
    options: {
      filter: false,
      sort: false,
      setCellHeaderProps: () => ({
        style: {
          display: 'none'
        }
      }),
      setCellProps: () => ({
        style: {
          width: '80px',
          minWidth: '80px',
          maxWidth: '80px'
        }
      }),
      customBodyRender: (value, tableMeta) => {
        const member = members[tableMeta.rowIndex];
        if (!member || !member.user) return null;
        const isOwner = member.userDid === org.ownerDid;
        if (!editable || isOwner) return null;
        return /*#__PURE__*/_jsx(Box, {
          sx: {
            py: {
              xs: 0.5,
              sm: 1
            },
            display: {
              xs: 'none',
              sm: 'block'
            }
          },
          children: /*#__PURE__*/_jsx(IconButton, {
            color: "error",
            "aria-label": "delete",
            title: t('team.orgs.invite.remove'),
            onClick: () => requests.removeOrgMember(org.id, member),
            children: /*#__PURE__*/_jsx(DeleteIcon, {})
          })
        });
      }
    }
  }];
  const tableOptions = {
    sort: false,
    download: false,
    filter: false,
    print: false,
    search: false,
    viewColumns: false,
    selectableRows: 'none',
    expandableRowsOnClick: false,
    page: paging.page - 1,
    rowsPerPage: paging.pageSize,
    count: paging.total || 0,
    pagination: paging.pageCount > 1
  };
  if (loading) {
    return /*#__PURE__*/_jsx(Box, {
      className: "members-list",
      children: /*#__PURE__*/_jsx(List, {
        sx: {
          width: '100%',
          bgcolor: 'background.paper'
        },
        children: Array.from({
          length: 3
        }, (_, index) => /*#__PURE__*/_jsx(MemberSkeleton, {
          index: index
        }, `skeleton-${index}`))
      })
    });
  }
  return /*#__PURE__*/_jsx(Box, {
    className: "members-list",
    sx: {
      width: '100%',
      '& .org-members-table > div': {
        overflow: 'hidden'
      },
      '& .MuiPaper-root': {
        overflow: {
          xs: 'hidden',
          sm: 'auto'
        }
      },
      '& table': {
        width: {
          xs: '100%',
          sm: 'auto'
        },
        tableLayout: {
          xs: 'fixed',
          sm: 'auto'
        }
      },
      '& .MuiTableRow-root .MuiTableCell-root': {
        py: {
          xs: 0.5,
          sm: 1
        }
      },
      '& tbody tr': {
        display: {
          xs: 'grid',
          sm: 'table-row'
        },
        gridTemplateColumns: {
          xs: '1fr',
          sm: 'auto'
        },
        gridTemplateRows: {
          xs: 'auto auto',
          sm: 'auto'
        },
        '& td': {
          display: {
            xs: 'block !important',
            sm: 'table-cell !important'
          },
          '&:nth-of-type(1)': {
            gridColumn: {
              xs: '1',
              sm: 'auto'
            },
            gridRow: {
              xs: '1',
              sm: 'auto'
            }
          },
          '&:nth-of-type(2)': {
            gridColumn: {
              xs: '1',
              sm: 'auto'
            },
            gridRow: {
              xs: '2',
              sm: 'auto'
            },
            minWidth: {
              xs: 0,
              sm: 'auto'
            }
          },
          '&:nth-of-type(3), &:nth-of-type(4)': {
            display: {
              xs: 'none !important',
              sm: 'table-cell !important'
            }
          }
        }
      }
    },
    children: /*#__PURE__*/_jsx(Datatable, {
      className: "org-members-table",
      data: members,
      columns: columns,
      loading: loading,
      onChange: onTableChange,
      locale: locale,
      options: tableOptions
    })
  });
}
export function MemberExtra() {
  const {
    t
  } = useLocaleContext();
  const {
    orgDetail,
    inviteParams
  } = useOrgsContext();
  const {
    invitations,
    editable,
    org
  } = orgDetail || {};
  if (!editable) {
    return null;
  }
  return /*#__PURE__*/_jsxs(Box, {
    sx: {
      display: 'flex',
      gap: 1
    },
    children: [/*#__PURE__*/_jsxs(Button, {
      variant: "outlined",
      style: {
        flexShrink: 0
      },
      color: "primary",
      size: "small",
      onClick: () => {
        inviteParams.onTriggerInvitingDialog({
          org,
          open: true
        });
      },
      children: [/*#__PURE__*/_jsx(Icon, {
        style: {
          height: '1em',
          marginRight: 4
        },
        icon: "tabler:user"
      }), t('common.inviting'), invitations.length ? ` (${invitations.length})` : '']
    }), /*#__PURE__*/_jsx(Button, {
      variant: "contained",
      size: "small",
      onClick: () => {
        inviteParams.onTriggerInviteDialog({
          org,
          open: true,
          mode: 'detail'
        });
      },
      startIcon: /*#__PURE__*/_jsx(Icon, {
        style: {
          fontSize: 14
        },
        icon: "tabler:user-plus"
      }),
      children: t('common.invite')
    })]
  });
}