import { FluxDispatcher } from '@vizality/webpack';
import { toPlural } from '@vizality/util/string';
import { error } from '@vizality/util/logger';
import React, { memo } from 'react';

import AsyncComponent from './AsyncComponent';

const Anchor = AsyncComponent.fromDisplayName('Anchor');

/**
 * @private
 */
const _labels = [ 'Component', 'Anchor' ];
const _error = (...message) => error({ labels: _labels, message });

export default memo(({ onClick, href, className, userId, children, type, addonId, ...other }) => {
  return (
    <Anchor
      {...other}
      className={className}
      vz-type={type}
      vz-user-id={userId}
      vz-addon-id={addonId}
      href={type === 'user' && userId
        ? `${window.location.origin}${$discord.constants.Endpoints.USERS}/${userId}`
        : type === 'plugin' || type === 'theme' && addonId
          ? `${window.location.origin}/vizality/${toPlural(type)}/${addonId}}`
          : href
      }
      onClick={async evt => {
        try {
          /**
           *
           */
          if (!userId && !addonId && !href) {
            if (!onClick) {
              return evt.preventDefault();
            }
            return onClick(evt);
          }

          /**
           *
           */
          if (href?.startsWith('#')) {
            evt?.preventDefault?.();
            const selector = document.querySelector(`#${href.substring(1) || 'none'}`);
            if (selector) {
              const topOfElement = selector.offsetTop;
              const scroller = document.querySelector('.vz-dashboard-scroller');
              /**
               * If the elements don't exist at the check, just load the page normally as if
               * there was no hash.
               */
              if (!topOfElement || !scroller) {
                return;
              }
              /**
               * Try to set the scroller position to the hash element.
               */
              return scroller.scroll({ top: topOfElement - 80, behavior: 'smooth' });
            }
          }

          /**
           *
           */
          if (type === 'user') {
            evt.preventDefault();
            const user = await $discord.users.fetchUser(userId);
            if (!user) {
              return vizality.api.notifications.sendToast({
                id: 'VIZALITY_USER_NOT_FOUND',
                header: 'User Not Found',
                content: 'That user was unable to be located.',
                icon: 'PersonRemove'
              });
            }
            return FluxDispatcher.dirtyDispatch({
              type: $discord.constants.ActionTypes.USER_PROFILE_MODAL_OPEN,
              userId
            });
          }

          /**
           *
           */
          if (type === 'plugin' || type === 'theme') {
            evt.preventDefault();
            return vizality.api.routes.navigateTo(`/vizality/${toPlural(type)}/${addonId}`);
          }
        } catch (err) {
          return _error(err);
        }
      }}
    >
      {children}
    </Anchor>
  );
});
