// @flow
import React, { type ComponentType } from 'react';
import styled from 'styled-components';
import { Story } from '@storybook/addon-docs/blocks';
import { linkTo } from '@storybook/addon-links';

import { Box, type BoxProps } from '../../../src/primitives/box';
import { Text } from '../../../src/core/typography/text';
import {
  UnstyledButton,
  type UnstyledButtonProps,
} from '../../../src/core/behaviors/unstyled-button';
import { getPaletteColor } from '../../../src/mixins/branding';

export type StoryPreviewProps = {
  /* The name of the component to be previewed. */
  name: string,

  /* The prefix of the story to be previewed. */
  kind: string,

  /* The name of the story to be previewed. */
  previewStory?: string,

  /* The name of the story to be linked to, if different. */
  linkToStory?: string,

  basis?: number,
};

export const StoryPreview = ({
  name,
  kind,
  previewStory,
  linkToStory,
  basis,
}: StoryPreviewProps) => (
  <RelativeBox
    spacing={['pv2', 'ph3', 'mr2', 'mv1']}
    stacked="column"
    basis={basis}
  >
    <Box grow={1} stacked="column" justify="space-between" align="stretch">
      <Box
        stacked="column"
        justify="center"
        align={basis != null ? 'stretch' : 'center'}
        grow={1}
        spacing="mb0"
      >
        {previewStory != null && <Story id={`${kind}--${previewStory}`} />}
      </Box>
      <Text spacing="m0" italic align="center">
        {name}
      </Text>
    </Box>
    <ClickableOverlay
      insetFocus
      onClick={linkTo(`${kind}--${linkToStory ?? previewStory ?? ''}`)}
    />
  </RelativeBox>
);

const RelativeBox: ComponentType<BoxProps> = styled(Box)`
  position: relative;
`;

const ClickableOverlay: ComponentType<UnstyledButtonProps> = styled(
  UnstyledButton,
)`
  border: solid 2px ${getPaletteColor('greyscale-light')};
  border-radius: 10px;
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;
  height: 100%;

  &:hover {
    border: solid 2px ${getPaletteColor('greyscale-medium')};
  }
`;
