/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable no-console */
import Tag from '@arcblock/ux/lib/Tag';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Box, CircularProgress, Icon, Link, styled, Tooltip, Typography } from '@mui/material';
import React, { useMemo } from 'react';
import isEmpty from 'lodash/isEmpty';
import dayjs from '@abtnode/util/lib/dayjs';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import { BACKUPS } from '@abtnode/constant';
import Datatable from '@arcblock/ux/lib/Datatable';
import xbytes from 'xbytes';
import InfoIcon from '@mui/icons-material/Info';
import PropTypes from 'prop-types';
import { getDIDSpaceDidFromEndpoint } from '../../../util/spaces';
import { useBlockletStorageContext } from '../../../contexts/blocklet-storage';

// 自定义无背景 Tooltip
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
const CustomTooltip = styled(({
  className,
  ...props
}) => /*#__PURE__*/_jsx(Tooltip, {
  ...props,
  classes: {
    popper: className
  }
}))(() => ({
  '.MuiTooltip-tooltip': {
    backgroundColor: 'transparent',
    padding: 0,
    margin: 0,
    boxShadow: 'none',
    maxWidth: 'none'
  },
  '.MuiTooltip-arrow': {
    color: 'rgba(230, 235, 245, 1)'
  }
}));

// 状态标签组件
function StatusTag({
  status,
  message = '',
  createdAt
}) {
  const {
    t
  } = useLocaleContext();
  const timeoutError = status === BACKUPS.STATUS.PROGRESS && dayjs().diff(createdAt, 'hours') >= BACKUPS.TIMEOUT_HOURS;
  const timeoutErrorMessage = timeoutError && t('common.timeoutError');
  const pending = status === BACKUPS.STATUS.PROGRESS && !timeoutError;
  const success = status === BACKUPS.STATUS.SUCCEEDED && !timeoutError;
  if (pending) {
    return /*#__PURE__*/_jsxs(Typography, {
      sx: {
        display: 'inline-flex',
        alignItems: 'center',
        fontSize: '14px'
      },
      children: [/*#__PURE__*/_jsx(CircularProgress, {
        sx: {
          marginRight: '4px'
        },
        size: "12px"
      }), t('common.progress')]
    });
  }
  if (success) {
    return /*#__PURE__*/_jsx(Tag, {
      type: "success",
      children: t('common.succeeded')
    });
  }
  return /*#__PURE__*/_jsxs(Box, {
    sx: {
      display: 'inline-flex',
      alignItems: 'center'
    },
    children: [/*#__PURE__*/_jsx(Tag, {
      type: "error",
      children: t('common.failed')
    }), /*#__PURE__*/_jsx(Tooltip, {
      style: {
        display: 'flex',
        alignItems: 'center',
        flexShrink: 0
      },
      title: message || timeoutErrorMessage,
      children: /*#__PURE__*/_jsx(Icon, {
        children: /*#__PURE__*/_jsx(HelpOutlineIcon, {
          style: {
            width: '24px',
            height: '24px'
          },
          color: "error"
        })
      })
    })]
  });
}
StatusTag.propTypes = {
  status: PropTypes.string.isRequired,
  message: PropTypes.string,
  createdAt: PropTypes.string.isRequired
};

// 成功状态带详情的标签组件
function SuccessStatusWithDetails({
  metadata = {}
}) {
  const {
    t
  } = useLocaleContext();
  if (isEmpty(metadata)) {
    return /*#__PURE__*/_jsx(Tag, {
      type: "success",
      children: t('common.succeeded')
    });
  }
  const fileCount = metadata.count || 0;
  const fileSize = metadata.size || 0;
  const formattedSize = xbytes(fileSize, {
    iec: true
  });
  const tooltipContent = /*#__PURE__*/_jsxs(Box, {
    sx: {
      p: 1,
      borderRadius: 1,
      boxShadow: 2,
      color: 'black',
      backgroundColor: 'white'
    },
    children: [/*#__PURE__*/_jsxs(Typography, {
      variant: "body2",
      children: [t('common.fileCount'), ": ", fileCount]
    }), /*#__PURE__*/_jsxs(Typography, {
      variant: "body2",
      children: [t('common.fileSize'), ": ", formattedSize]
    })]
  });
  return /*#__PURE__*/_jsxs(Box, {
    sx: {
      display: 'inline-flex',
      alignItems: 'center'
    },
    children: [/*#__PURE__*/_jsx(Tag, {
      type: "success",
      children: t('common.succeeded')
    }), /*#__PURE__*/_jsx(CustomTooltip, {
      title: tooltipContent,
      style: {
        display: 'flex',
        alignItems: 'center',
        flexShrink: 0
      },
      placement: "left",
      children: /*#__PURE__*/_jsx(Icon, {
        children: /*#__PURE__*/_jsx(InfoIcon, {
          style: {
            width: '24px',
            height: '24px'
          },
          color: "primary"
        })
      })
    })]
  });
}
SuccessStatusWithDetails.propTypes = {
  metadata: PropTypes.object
};
function SpacesBackupRecordsTable() {
  const {
    t,
    locale
  } = useLocaleContext();
  const {
    spaceGateways,
    backups,
    backupsLoading
  } = useBlockletStorageContext();

  // 表格列定义
  const columns = useMemo(() => [{
    label: 'DID Space',
    name: 'target',
    options: {
      customBodyRenderLite: index => {
        const {
          targetUrl,
          targetName,
          status,
          createdAt
        } = backups[index];
        const timeoutError = status === BACKUPS.STATUS.PROGRESS && dayjs().diff(createdAt, 'hours') >= BACKUPS.TIMEOUT_HOURS;
        const success = status === BACKUPS.STATUS.SUCCEEDED && !timeoutError;
        const spaceName = targetName || spaceGateways.find(spaceGateway => targetUrl?.includes(getDIDSpaceDidFromEndpoint(spaceGateway?.endpoint)))?.name || 'Unknown DID Space';
        if (!success) {
          return /*#__PURE__*/_jsx(Typography, {
            variant: "body1",
            sx: {
              fontSize: '16px'
            },
            children: spaceName
          });
        }
        return /*#__PURE__*/_jsx(Link, {
          href: targetUrl,
          target: "_blank",
          sx: {
            fontSize: '16px'
          },
          children: spaceName
        });
      }
    }
  }, {
    label: t('common.strategy'),
    name: 'strategy',
    options: {
      customBodyRender: strategy => {
        const text = strategy === 0 ? t('common.auto') : t('common.manual');
        return /*#__PURE__*/_jsx(Tag, {
          children: text
        });
      }
    }
  }, {
    label: t('common.startTime'),
    name: 'createdAt',
    options: {
      customBodyRender: createdAt => dayjs(createdAt).format('YYYY-MM-DD HH:mm:ss')
    }
  }, {
    label: t('common.endTime'),
    name: 'updatedAt',
    options: {
      customBodyRender: updatedAt => isEmpty(updatedAt) ? '' : dayjs(updatedAt).format('YYYY-MM-DD HH:mm:ss')
    }
  }, {
    label: t('common.status'),
    name: 'status',
    options: {
      customBodyRenderLite: index => {
        const record = backups?.[index] ?? {};
        const {
          status,
          message,
          createdAt,
          metadata
        } = record;
        const timeoutError = status === BACKUPS.STATUS.PROGRESS && dayjs().diff(createdAt, 'hours') >= BACKUPS.TIMEOUT_HOURS;
        const pending = status === BACKUPS.STATUS.PROGRESS && !timeoutError;
        const success = status === BACKUPS.STATUS.SUCCEEDED && !timeoutError;
        if (pending) {
          return /*#__PURE__*/_jsxs(Typography, {
            sx: {
              display: 'inline-flex',
              alignItems: 'center',
              fontSize: '14px'
            },
            children: [/*#__PURE__*/_jsx(CircularProgress, {
              sx: {
                marginRight: '4px'
              },
              size: "12px"
            }), t('common.progress')]
          });
        }
        if (success) {
          return /*#__PURE__*/_jsx(SuccessStatusWithDetails, {
            metadata: metadata
          });
        }
        return /*#__PURE__*/_jsx(StatusTag, {
          status: status,
          message: message,
          createdAt: createdAt
        });
      }
    }
  }], [backups, spaceGateways, t]);
  const showEmptyState = useMemo(() => {
    return !backups?.length;
  }, [backups]);
  return (
    /*#__PURE__*/
    // eslint-disable-next-line react/jsx-no-useless-fragment
    _jsx(_Fragment, {
      children: showEmptyState ? /*#__PURE__*/_jsx(Box, {
        sx: {
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100px',
          color: '#9397A1',
          marginTop: '16px',
          marginBottom: '24px'
        },
        children: t('storage.spaces.record.emptyData')
      }) : /*#__PURE__*/_jsx(Datatable, {
        title: "",
        loading: backupsLoading,
        data: backups,
        columns: columns,
        emptyNode: t('storage.spaces.record.emptyData', locale),
        options: {
          download: false,
          filter: false,
          print: false,
          search: false,
          viewColumns: false
        }
      })
    })
  );
}
export default SpacesBackupRecordsTable;