// @flow
import React from 'react';
import styled from 'styled-components';
import type { NextButtonProps } from './next-button.proptypes';
import { Span } from '../../typography';
import { NextIcon } from '../../icon';
import { getFontFamily } from '../../../mixins/typography';
import { getPaletteColor } from '../../../mixins/branding';
import {
  FOCUS_VISIBLE_SELECTOR,
  transitionInstant,
  transitionFade,
  getBaseFocusState,
  focusedBoxShadow,
  focusedBorderShadow,
  focusedBorderColor,
} from '../../../mixins/focus';
import { Spinner } from '../../feedback-ui/spinner';

// Needs to be a button for accessibility, form-next semantic reasons.
const StyledButton = styled.button`
  background: none;
  border: none;
  display: flex;
  align-items: center;
  color: inherit;
  font-size: inherit;
  margin: 6px;

  ${getBaseFocusState({ activeTransition: false })}
  svg > g > g {
    transition: ${transitionFade};
  }
  ${FOCUS_VISIBLE_SELECTOR} {
    svg {
      box-shadow: ${focusedBorderShadow({ inset: false })} ${focusedBorderColor},
        ${focusedBoxShadow};
      border-radius: 50%;
    }
  }
  &[disabled] {
    cursor: default;
  }
  &:not([disabled]):hover {
    svg > g > g {
      fill: ${getPaletteColor('brand-primary-base-hover')};
      transition: ${transitionInstant};
    }
  }
  &:not([disabled]):active {
    svg > g > g {
      fill: ${getPaletteColor('brand-primary-base')};
      transition: ${transitionInstant};
    }
  }
`;

const OffsetSpan = styled(Span)`
  font-family: ${getFontFamily};
  padding-right: 22px;
`;

const Circle = styled.div`
  align-items: center;
  background: ${getPaletteColor('brand-primary-base')};
  border-radius: 50%;
  color: ${getPaletteColor('white')};
  display: inline-flex;
  justify-content: center;
  height: 48px;
  width: 48px;
`;

export const NextButton = ({
  children,
  disabled = false,
  isLoading = false,
  spacing,
  className,
  'data-cy': dataCy,
  'data-qa': dataQa,
  id,
  ...props
}: NextButtonProps) => (
  <StyledButton
    type="submit"
    disabled={disabled || isLoading}
    spacing={spacing}
    className={className}
    data-cy={dataCy}
    data-qa={dataQa}
    id={id}
    {...props}
  >
    {children != null ? (
      <OffsetSpan fontSize="f2" bold colorName="greyscale-dark">
        {children}
      </OffsetSpan>
    ) : null}
    {isLoading ? (
      <Circle>
        <Spinner />
      </Circle>
    ) : (
      <NextIcon disabled={disabled} />
    )}
  </StyledButton>
);

NextButton.displayName = 'NextButton';
