/* eslint-disable react/require-default-props */

import Button from '@arcblock/ux/lib/Button';
import styled from '@emotion/styled';
import PropTypes from 'prop-types';
import trim from 'lodash/trim';
import React, { useCallback, useMemo, useState } from 'react';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import Box from '@mui/material/Box';
import Tooltip from '@mui/material/Tooltip';
import Spinner from '@mui/material/CircularProgress';
import useMediaQuery from '@mui/material/useMediaQuery';
import Empty from '@arcblock/ux/lib/Empty';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { CopyButton } from '@arcblock/ux/lib/ClickToCopy';
import { Domain as DomainComponent } from '@blocklet/did-domain-react';
import { Typography, Paper, Stack, useTheme } from '@mui/material';
import { isCustomDomain } from '@abtnode/util/lib/url-evaluation';
import { useBlockletContext } from '../../contexts/blocklet';
import { useNodeContext } from '../../contexts/node';
import { withPermission } from '../../permission';
import { BlockletAdminRoles, sortDomains } from '../../util';
import AddCert from '../add-cert';
import DomainActions from '../router/domain-actions';
import DomainStatus from '../router/domain-status';
import { DomainType } from '../types';
import { isServerless } from '../util';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
const BlockletComponent = withPermission(DomainList, 'mutate_blocklets');
const BlockletInServiceComponent = withPermission(DomainList, '', BlockletAdminRoles);
export default function DomainListWithPermission(props) {
  const {
    inService
  } = useNodeContext();
  const {
    blocklet,
    loadingRuntimeInfo
  } = useBlockletContext();
  let Component = BlockletComponent;
  if (inService) {
    Component = BlockletInServiceComponent;
  }
  return /*#__PURE__*/_jsx(Component, {
    ...props,
    blocklet: blocklet,
    inService: inService,
    loadingRuntimeInfo: loadingRuntimeInfo
  });
}
const DIDDomainType = 'nft-domain';
const DIDDomainForwardingType = 'nft-domain-forwarding';
function DomainList({
  hasPermission = false,
  blocklet,
  loadingRuntimeInfo = false,
  inService = false,
  showAllDomains = false,
  updateBlockletDomainAliases = () => {},
  systemTips = null
}) {
  const {
    t
  } = useLocaleContext();
  const isMobile = useMediaQuery(x => x.breakpoints.down('md'));
  const hasMutatePermission = useMemo(() => {
    let res = hasPermission;
    if (isServerless(blocklet)) {
      res = res && inService;
    }
    return res;
  }, [hasPermission, inService, blocklet]);
  const {
    site
  } = blocklet;
  const domains = useMemo(() => sortDomains(blocklet.site?.domainAliases), [blocklet.site?.domainAliases]);
  const systemDomains = useMemo(() => domains.filter(domain => !isCustomDomain(domain.value)), [domains]);
  const customDomains = useMemo(() => domains.filter(domain => isCustomDomain(domain.value)), [domains]);
  const manualDomains = useMemo(() => customDomains.filter(domain => domain.type !== DIDDomainType && domain.type !== DIDDomainForwardingType), [customDomains]);
  const DIDDomains = useMemo(() => customDomains.filter(domain => domain.type === DIDDomainType), [customDomains]);
  const forwardingDomains = useMemo(() => customDomains.filter(domain => domain.type === DIDDomainForwardingType), [customDomains]);
  return /*#__PURE__*/_jsxs(_Fragment, {
    children: [/*#__PURE__*/_jsxs(Stack, {
      sx: {
        gap: 3
      },
      children: [!!DIDDomains.length && /*#__PURE__*/_jsx(DomainURLCard, {
        title: t('common.didDomains'),
        description: t('common.didDomainsDescription'),
        domains: DIDDomains,
        hasMutatePermission: hasMutatePermission,
        blocklet: blocklet,
        site: site,
        mobile: isMobile,
        showAllDomains: showAllDomains,
        updateBlockletDomainAliases: updateBlockletDomainAliases
      }), !!forwardingDomains.length && /*#__PURE__*/_jsx(DomainURLCard, {
        title: t('common.forwardingDomains'),
        description: t('common.forwardingDomainsDescription'),
        domains: forwardingDomains,
        hasMutatePermission: hasMutatePermission,
        blocklet: blocklet,
        site: site,
        mobile: isMobile,
        showAllDomains: showAllDomains,
        updateBlockletDomainAliases: updateBlockletDomainAliases
      }), !!manualDomains.length && /*#__PURE__*/_jsx(DomainURLCard, {
        title: t('common.manualDomains'),
        description: t('common.manualDomainsDescription'),
        domains: manualDomains,
        hasMutatePermission: hasMutatePermission,
        blocklet: blocklet,
        site: site,
        mobile: isMobile,
        showAllDomains: showAllDomains,
        updateBlockletDomainAliases: updateBlockletDomainAliases
      }), !!systemDomains.length && /*#__PURE__*/_jsxs(Box, {
        children: [systemTips, /*#__PURE__*/_jsx(DomainURLCard, {
          title: t('common.systemDomains'),
          description: t('common.systemDomainsDescription'),
          domains: systemDomains,
          hasMutatePermission: hasMutatePermission,
          blocklet: blocklet,
          site: site,
          mobile: isMobile,
          updateBlockletDomainAliases: updateBlockletDomainAliases
        })]
      })]
    }), !domains.length && (loadingRuntimeInfo ? /*#__PURE__*/_jsx(Spinner, {
      size: 16
    }) : /*#__PURE__*/_jsx(Empty, {
      children: t('common.empty')
    }))]
  });
}
DomainList.propTypes = {
  hasPermission: PropTypes.bool,
  blocklet: PropTypes.object.isRequired,
  loadingRuntimeInfo: PropTypes.bool,
  inService: PropTypes.bool.isRequired,
  showAllDomains: PropTypes.bool,
  updateBlockletDomainAliases: PropTypes.func,
  systemTips: PropTypes.node
};
function DomainLinkSuffix({
  children = null
}) {
  return /*#__PURE__*/_jsx(Box, {
    component: "span",
    sx: {
      verticalAlign: 'bottom'
    },
    children: children
  });
}
DomainLinkSuffix.propTypes = {
  children: PropTypes.node
};
function DomainLink({
  domain,
  children,
  suffix = null,
  ...rest
}) {
  const {
    t,
    locale
  } = useLocaleContext();
  const theme = useTheme();
  const {
    href,
    accessibility,
    value: domainValue
  } = domain;
  const renderCopyButton = useCallback(() => {
    return /*#__PURE__*/_jsx(CopyButton, {
      content: trim(domainValue),
      locale: locale,
      style: {
        marginLeft: '4px',
        color: theme.palette.text.secondary,
        fontSize: '0.8em'
      }
    });
  }, [domainValue, locale, theme]);
  if (!accessibility || accessibility.loading) {
    return /*#__PURE__*/_jsxs(LinkDiv, {
      component: "span",
      ...rest,
      children: [/*#__PURE__*/_jsx(Tooltip, {
        title: undefined,
        placement: "top-end",
        children: /*#__PURE__*/_jsx(Box, {
          component: "span",
          children: children
        })
      }), renderCopyButton(), /*#__PURE__*/_jsx(DomainLinkSuffix, {
        children: suffix
      }), /*#__PURE__*/_jsx(Tooltip, {
        title: t('blocklet.router.checkUrlAccessible'),
        placement: "top-end",
        children: /*#__PURE__*/_jsx(Box, {
          component: "span",
          className: "status",
          children: /*#__PURE__*/_jsx(Spinner, {
            size: 13,
            style: {
              fontSize: '13px'
            }
          })
        })
      })]
    });
  }
  if (!accessibility.accessible) {
    return /*#__PURE__*/_jsxs(LinkDiv, {
      component: "span",
      ...rest,
      children: [/*#__PURE__*/_jsx(Tooltip, {
        title: t('blocklet.router.urlInaccessible'),
        placement: "top-end",
        children: /*#__PURE__*/_jsx(Box, {
          component: "span",
          children: children
        })
      }), !domain.loading && renderCopyButton(), /*#__PURE__*/_jsx(DomainLinkSuffix, {
        children: suffix
      })]
    });
  }
  return /*#__PURE__*/_jsxs(LinkDiv, {
    component: "span",
    ...rest,
    children: [/*#__PURE__*/_jsx(Box, {
      component: "a",
      href: href,
      target: "_blank",
      rel: "noopener noreferrer",
      sx: {
        color: domain.loading ? 'text.disabled' : undefined
      },
      children: /*#__PURE__*/_jsx(Tooltip, {
        title: undefined,
        placement: "top-end",
        children: /*#__PURE__*/_jsx(Box, {
          component: "span",
          children: children
        })
      })
    }), renderCopyButton(), /*#__PURE__*/_jsx(DomainLinkSuffix, {
      children: suffix
    })]
  });
}
DomainLink.propTypes = {
  domain: DomainType.isRequired,
  children: PropTypes.any.isRequired,
  suffix: PropTypes.node
};
const LinkDiv = styled(Box)`
  display: inline-block;
  vertical-align: middle;

  & > span {
    line-height: 24px;
  }

  &,
  & > * {
    color: ${({
  theme
}) => theme.palette.text.primary};
    font-size: 18px;
  }

  &,
  & > * {
    word-break: break-all;
  }

  svg {
    vertical-align: text-top;
  }

  .status {
    margin-left: 8px;
    font-size: 13px;
  }
`;
function InnerAction({
  hasMutatePermission,
  site,
  domain,
  blocklet,
  onDelete
}) {
  if (hasMutatePermission && !domain.isProtected) {
    return /*#__PURE__*/_jsx(DomainActions, {
      site: site,
      domain: domain,
      blocklet: blocklet,
      onDelete: onDelete
    });
  }
  return null;
}
InnerAction.propTypes = {
  hasMutatePermission: PropTypes.bool.isRequired,
  site: PropTypes.object.isRequired,
  domain: DomainType.isRequired,
  blocklet: PropTypes.object.isRequired,
  onDelete: PropTypes.func.isRequired
};
function InnerAddDomain({
  siteId,
  domain,
  blocklet,
  hasMutatePermission
}) {
  const {
    info
  } = useNodeContext();
  const {
    t,
    locale
  } = useLocaleContext();
  const [issuing, setIssuing] = useState(false);
  return /*#__PURE__*/_jsxs(Box, {
    sx: {
      display: 'flex',
      justifyContent: 'flex-start',
      alignItems: 'center',
      gap: 0.5,
      button: {
        lineHeight: 1
      }
    },
    children: [domain.type === 'nft-domain' && /*#__PURE__*/_jsx(DomainComponent, {
      locale: locale,
      nftDid: domain.nftDid,
      didDomainURL: info.nftDomainUrl
    }), /*#__PURE__*/_jsx(Box, {
      sx: {
        display: 'flex',
        mt: '-1px'
      },
      children: /*#__PURE__*/_jsx(DomainStatus, {
        domain: domain,
        filters: ['http']
      }, `${domain.value}-http`)
    }), hasMutatePermission && domain.canGenerateCertificate && /*#__PURE__*/_jsx(AddCert, {
      siteId: siteId,
      domain: domain.value,
      domainStatus: domain.domainStatus,
      did: blocklet.meta.did,
      issuing: issuing,
      setIssuing: setIssuing,
      children: ({
        open
      }) => /*#__PURE__*/_jsx(Button, {
        sx: {
          padding: 0
        },
        size: "small",
        onClick: e => open(e),
        children: t('router.cert.genLetsEncryptCert.title')
      })
    })]
  });
}
InnerAddDomain.propTypes = {
  siteId: PropTypes.string.isRequired,
  domain: DomainType.isRequired,
  blocklet: PropTypes.object.isRequired,
  hasMutatePermission: PropTypes.bool.isRequired
};
function DomainURLCard({
  title,
  description,
  domains = [],
  hasMutatePermission,
  blocklet,
  site,
  mobile,
  showAllDomains = false,
  updateBlockletDomainAliases = () => {}
}) {
  const [expanded, setExpanded] = useState(false);
  const displayDomains = useMemo(() => {
    if (showAllDomains) {
      return domains;
    }
    return expanded ? domains : domains.slice(0, 1);
  }, [domains, expanded, showAllDomains]);
  const hasMoreDomains = domains.length > 1;
  const isProtectedDomain = domain => hasMutatePermission && !domain.isProtected;
  return /*#__PURE__*/_jsx(Paper, {
    elevation: 0,
    sx: {
      p: 3,
      pb: showAllDomains ? 3 : 1.5,
      display: 'flex',
      alignItems: 'flex-start',
      gap: 3,
      borderRadius: 2,
      border: '1px solid',
      borderColor: 'divider',
      transition: 'box-shadow 0.2s ease-in-out'
    },
    children: /*#__PURE__*/_jsxs(Stack, {
      sx: {
        width: 1
      },
      children: [/*#__PURE__*/_jsxs(Box, {
        sx: {
          mb: 1.5
        },
        children: [/*#__PURE__*/_jsx(Typography, {
          variant: "h6",
          children: title
        }), /*#__PURE__*/_jsx(Typography, {
          sx: {
            fontSize: 12,
            color: 'text.secondary',
            mt: 0.5
          },
          children: description
        })]
      }), displayDomains.map((domain, index) => /*#__PURE__*/_jsxs(Stack, {
        children: [index !== 0 && /*#__PURE__*/_jsx(Box, {
          sx: {
            my: 0.75,
            width: 1,
            height: '1px'
          }
        }), !mobile && /*#__PURE__*/_jsxs(Box, {
          sx: {
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between'
          },
          children: [/*#__PURE__*/_jsxs(Box, {
            sx: {
              display: 'flex',
              alignItems: 'center',
              gap: 1
            },
            children: [/*#__PURE__*/_jsx(Box, {
              sx: {
                height: 28,
                display: 'flex',
                alignItems: 'center'
              },
              children: /*#__PURE__*/_jsx(DomainStatus, {
                domain: domain,
                filters: ['domain']
              }, `${domain.value}-domain`)
            }), /*#__PURE__*/_jsxs(Box, {
              sx: {
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'flex-start',
                gap: 0.5,
                svg: {
                  width: '1em',
                  height: '1em'
                },
                img: {
                  width: '0.9em',
                  height: '0.9em'
                }
              },
              children: [/*#__PURE__*/_jsx(DomainLink, {
                domain: domain,
                target: "_blank",
                children: domain.value
              }), /*#__PURE__*/_jsx(Box, {
                sx: {
                  mt: '2px'
                },
                children: /*#__PURE__*/_jsx(InnerAddDomain, {
                  siteId: blocklet.site?.id,
                  domain: domain,
                  blocklet: blocklet,
                  hasMutatePermission: hasMutatePermission
                })
              })]
            })]
          }), /*#__PURE__*/_jsx(Box, {
            sx: {
              button: {
                padding: 0
              }
            },
            children: /*#__PURE__*/_jsx(InnerAction, {
              hasMutatePermission: hasMutatePermission,
              site: site,
              domain: domain,
              blocklet: blocklet,
              onDelete: () => updateBlockletDomainAliases(domain, 'delete')
            })
          })]
        }), mobile && /*#__PURE__*/_jsxs(Box, {
          sx: {
            display: 'flex',
            flexDirection: 'column'
          },
          children: [/*#__PURE__*/_jsxs(Box, {
            sx: {
              display: 'flex',
              justifyContent: 'flex-start',
              gap: 1
            },
            children: [/*#__PURE__*/_jsx(Box, {
              sx: {
                height: 28,
                display: 'flex',
                alignItems: 'center'
              },
              children: /*#__PURE__*/_jsx(DomainStatus, {
                domain: domain,
                filters: ['domain']
              }, `${domain.value}-domain`)
            }), /*#__PURE__*/_jsx(DomainLink, {
              domain: domain,
              target: "_blank",
              suffix: isProtectedDomain(domain) ? null : /*#__PURE__*/_jsx(Box, {
                sx: {
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  svg: {
                    width: '1em',
                    height: '1rem'
                  },
                  img: {
                    width: '0.9rem',
                    height: '0.9rem'
                  }
                },
                children: /*#__PURE__*/_jsx(InnerAddDomain, {
                  siteId: blocklet.site?.id,
                  domain: domain,
                  blocklet: blocklet,
                  hasMutatePermission: hasMutatePermission
                })
              }),
              children: domain.value
            })]
          }), isProtectedDomain(domain) && /*#__PURE__*/_jsxs(Box, {
            sx: {
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              ml: '18px'
            },
            children: [/*#__PURE__*/_jsx(Box, {
              sx: {
                display: 'flex',
                alignItems: 'center'
              },
              children: /*#__PURE__*/_jsx(InnerAddDomain, {
                siteId: blocklet.site?.id,
                domain: domain,
                blocklet: blocklet,
                hasMutatePermission: hasMutatePermission
              })
            }), /*#__PURE__*/_jsx(Box, {
              sx: {
                button: {
                  padding: 0
                }
              },
              children: /*#__PURE__*/_jsx(InnerAction, {
                hasMutatePermission: hasMutatePermission,
                site: site,
                domain: domain,
                blocklet: blocklet,
                onDelete: () => updateBlockletDomainAliases(domain, 'delete')
              })
            })]
          })]
        })]
      }, domain.value)), hasMoreDomains && !showAllDomains && /*#__PURE__*/_jsx(Button, {
        onClick: () => setExpanded(!expanded),
        sx: {
          p: 0,
          mt: 0.5,
          alignSelf: 'center'
        },
        children: expanded ? /*#__PURE__*/_jsx(ExpandLess, {}) : /*#__PURE__*/_jsx(ExpandMore, {})
      })]
    })
  });
}
DomainURLCard.propTypes = {
  title: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
  domains: PropTypes.array.isRequired,
  hasMutatePermission: PropTypes.bool.isRequired,
  blocklet: PropTypes.object.isRequired,
  site: PropTypes.object.isRequired,
  mobile: PropTypes.bool.isRequired,
  showAllDomains: PropTypes.bool,
  updateBlockletDomainAliases: PropTypes.func
};