import React, { ReactElement, ReactChild } from 'react';
import { css } from 'styled-components/macro';
import { Popover, PopoverMenu, PopoverMenuItem, PopoverToggle } from '@thewing/components';
import { CalendarExport, CalendarEvent } from 'services/CalendarExport';

const popoverButton = css`
  background: transparent;
  border: none;
  padding: 0;
`;

const popoverMenuStyle = css`
  #popover-menu-arrow {
    &::after {
      background: var(--navy);
    }
  }

  #popover-menu {
    background: var(--navy);
  }
`;

const popoverMenuItemStyle = css`
  color: var(--white);
  &:hover,
  &:focus-within {
    background: var(--white);
    color: var(--navy);
  }
`;

type CalOptions = {
  show: boolean;
  text: string;
};

type Props = {
  children?: ReactChild;
  event: CalendarEvent;
  types: {
    apple?: CalOptions;
    google?: CalOptions;
    outlookcom?: CalOptions;
  };
};

const defaultTypes = {
  apple: {
    show: true,
    text: 'Add to Apple',
  },
  google: {
    show: true,
    text: 'Add to Google',
  },
  outlookcom: {
    show: true,
    text: 'Add to Outlook',
  },
};

const ExportToCalendar = ({ types = defaultTypes, event, children }: Props): ReactElement => {
  const cal = new CalendarExport(event);

  return (
    <Popover>
      <PopoverToggle css={popoverButton}>{children}</PopoverToggle>
      <PopoverMenu css={popoverMenuStyle}>
        {Object.entries(types)
          .filter(([_key, value]: [string, CalOptions | undefined]) => value?.show)
          .map(([key, value]: [string, CalOptions | undefined]) => (
            <PopoverMenuItem
              css={popoverMenuItemStyle}
              onSelect={() => cal.onExportEvent(key)}
            >
              {value?.text}
            </PopoverMenuItem>
          ))}
      </PopoverMenu>
    </Popover>
  );
};

export { ExportToCalendar };
