import type { FC, ReactNode } from 'react';
import type { MenuDialogItem, MenuDialogSection } from './types';

import Box from '~/src/components/Box';
import Clickable from '~/src/components/Clickable';
import Text from '~/src/components/Text';
import wait from '~/src/lib/utils/wait';

export interface MenuDialogItemsProps {
  sections: (MenuDialogSection | false)[];
  baseFontSize?: string | number;
  onSelect: () => Promise<void>;
}

const MenuDialogItems: FC<MenuDialogItemsProps> = ({
  sections,
  baseFontSize,
  onSelect,
}) => {
  return (
    <ul
      style={{
        padding: '0.2em 0',
        fontSize: baseFontSize,
      }}
    >
      {(sections.filter(Boolean) as MenuDialogSection[]).reduce(
        (result, sectionItems, index) => {
          const Items = (sectionItems.filter(Boolean) as MenuDialogItem[]).map(
            ({ content, onClick, href, Icon, testId }, index) => {
              return (
                <Box tag="li" key={index}>
                  <Clickable
                    onClick={async () => {
                      onSelect();

                      if (onClick) {
                        // Give time for the dialog to close before opening
                        // another one to ensure if another Dialog is opened
                        // the `useKeyboard()` unmount logic has run before
                        // the mount logic of the next dialog runs to ensure
                        // focus is on the dialog content.
                        await wait(200);

                        onClick();
                      }
                    }}
                    href={href}
                    flexRow
                    alignCenter
                    height="1.41em"
                    testId={testId}
                  >
                    <Icon margin="0 0.36em 0 0" size="1em" />
                    <Text
                      size="0.74em"
                      lineHeight="1.3em"
                      flexGrow
                      withEllipsis
                      letterSpacing={0.035}
                    >
                      {content}
                    </Text>
                  </Clickable>
                </Box>
              );
            }
          );

          if (!Items.length) return result;

          return [
            ...result,
            <Box key={`section${index}`} tag="li" padding="0.3em 0.8em">
              <ul>{Items}</ul>
            </Box>,
          ];
        },
        [] as ReactNode[]
      )}
      <style jsx>{`
        ul {
          color: #ccc;
        }

        ul :global(a:hover),
        ul :global(button:hover) {
          color: #fff;
        }
      `}</style>
    </ul>
  );
};

export default MenuDialogItems;
