import { useRef, useState } from 'react';
import { AppIcon } from '@theorchard/suite-icons';

import type { FC } from 'react';

import { OrchardBrands } from '~/lib/songwhipApi/types';
import AnchoredDialog from '~/src/components/AnchoredDialog';
import Box from '~/src/components/Box';
import Clickable from '~/src/components/Clickable';
import HoverBackground from '~/src/components/HoverBackground';
import AppsIcon from '~/src/components/Icon/AppsIcon';
import Text from '~/src/components/Text';
import { useI18n } from '~/src/lib/i18n';
import { getOrchardUserApplicationsApi } from '~/src/lib/songwhipApi/users/getOrchardUserApplications';
import { useTracker } from '~/src/lib/tracker/useTracker';
import toFetchHook from '~/src/lib/utils/toFetchHook';

const useFetchOrchardApplications = toFetchHook(getOrchardUserApplicationsApi);

const OrchardAppSwitcher: FC<{
  userId: number;
  orchardBrand?: OrchardBrands;
}> = ({ userId, orchardBrand = OrchardBrands.ORCHARD }) => {
  const [isOpen, setIsOpen] = useState(false);
  const { trackEvent } = useTracker();
  const { t } = useI18n('app');
  const elRef = useRef(null);

  const { result: applications, isLoading } = useFetchOrchardApplications(
    { userId },
    [userId]
  );

  return (
    <>
      <Box nodeRef={elRef} fullHeight>
        <HoverBackground>
          <Clickable
            flexRow
            alignCenter
            testId="orchardAppSwitcher"
            isDisabled={isLoading}
            padding="0 1.7em"
            fullHeight
            onClick={() => setIsOpen(true)}
          >
            <AppsIcon margin="0 .8em 0 0" />
            <Text size="1.5em" isBold>
              {t('sideNav.applications')}
            </Text>
          </Clickable>
        </HoverBackground>
      </Box>
      {isOpen && (
        <AnchoredDialog
          xPosition="left"
          yPosition="top"
          zIndex={2}
          targetElRef={elRef}
          matchTargetElWidth
          withTriangle={false}
          color="#fff"
          style={{
            borderRadius: 0,
            background: 0,
          }}
          renderContent={() => (
            <Box
              margin="0 1rem"
              padding="0.5rem 1rem 2.5rem"
              style={{ borderRadius: '0.5rem', background: '#fff' }}
              flexRow
              flexWrap
            >
              {applications
                ?.filter(({ id }) => id !== 'SONGWHIP_APP')
                .map(({ name, id, url }) => (
                  <AppSwitcherIcon
                    key={id}
                    url={url ?? '#'}
                    brand={orchardBrand}
                    app={id.replace('_APP', '').toLowerCase()}
                    text={name}
                    onClick={() => {
                      trackEvent({
                        type: 'switch-app',
                        appName: name,
                      });
                    }}
                  />
                ))}
            </Box>
          )}
          onClose={() => setIsOpen(false)}
        />
      )}
      {/* HACK: Color the suite-icons. We must resort to this as we're
      not bundling the css from @theorchard/suite-icons */}
      <style global jsx>{`
        :root {
          --app-icon-gradient-color-0: #ff9f2b;
          --app-icon-gradient-color-1: #f04861;
        }
      `}</style>
    </>
  );
};

const AppSwitcherIcon: FC<{
  brand: string;
  app: string;
  text: string;
  url: string;
  onClick?(): void;
}> = ({ brand, text, app, url, onClick }) => (
  <Clickable
    href={url}
    style={{ width: '33%' }}
    testId="appSwitcherItem"
    onClick={onClick}
  >
    <Box padding="1.8rem 0.8rem 0" flexColumn centerContent>
      <AppIcon brand={brand} app={app} />
      <div style={{ width: '100%' }}>
        <Text
          size="1.1rem"
          margin="0.7rem 0 0"
          color="#000"
          lineHeight="1.3em"
          withEllipsis
          centered
        >
          {text}
        </Text>
      </div>
    </Box>
    <style jsx>{`
      div :global(svg) {
        width: 100%;
      }
    `}</style>
  </Clickable>
);

export default OrchardAppSwitcher;
