import { useCallback } from 'react';

import type { FC, ReactNode } from 'react';
import type { ModalProps } from '../Modal';

import Box from '../Box';
import Clickable from '../Clickable';
import Modal from '../Modal';
import Text from '../Text';

export type ModalActionItem = {
  content: ReactNode;
  onClick?: () => void;
  href?: string;
  testId?: string;
};

// extend the ModalProps, but remove the required `renderContent` prop
// as ModalActions accepts content via `items` prop.
export interface ModalActionsProps extends Omit<ModalProps, 'renderContent'> {
  items?: (ModalActionItem | boolean | undefined)[];
}

const ModalActions: FC<ModalActionsProps> = ({ items, ...props }) => {
  return (
    <Modal
      {...props}
      renderContent={useCallback(
        ({ close }) => {
          return (
            <Box className="inner" tag="ul">
              {(items?.filter(Boolean) as ModalActionItem[]).map(
                ({ content, onClick = () => {}, href, testId }, index) => (
                  <Box key={index} tag="li" padding="0 0 1.8rem">
                    <Clickable
                      onClick={async () => {
                        await close();
                        onClick();
                      }}
                      href={href}
                      testId={testId}
                      fullWidth
                    >
                      <Text size="2.8rem" bold centered>
                        {content}
                      </Text>
                    </Clickable>
                  </Box>
                )
              )}
            </Box>
          );
        },
        [items]
      )}
    />
  );
};

export default ModalActions;
