// @flow
import styled from 'styled-components';
import type { ThemeProps } from '../../../types';
import { getPaletteColor } from '../../../mixins/branding';
import {
  getFontFamily,
  getFontSize,
  getFontWeight,
} from '../../../mixins/typography';
import { getChevronDownDataUri } from '../../icon/chevrons/chevron-down/chevron-down.css-rules';
import {
  FOCUS_VISIBLE_SELECTOR,
  getBaseFocusState,
} from '../../../mixins/focus';

const getForegroundFont = ({ theme }: ThemeProps) => getFontFamily({ theme });

const getForegroundColor = ({
  theme,
  error,
  disabled,
}: {|
  ...ThemeProps,
  error?: boolean,
  disabled?: boolean,
|}) => {
  if (disabled) return getPaletteColor('greyscale-light')({ theme });
  if (error) return getPaletteColor('error-fg')({ theme });
  return getPaletteColor(theme.defaultTextColor || 'greyscale-black')({
    theme,
  });
};

const getFormSelectFontWeight = ({ large }: {| large?: boolean |}) =>
  getFontWeight({ bold: large });

const getFormSelectFontSize = ({
  theme,
  large,
}: {|
  ...ThemeProps,
  large?: boolean,
|}) => getFontSize({ theme, fontSize: large ? 'f2' : 'f1' });

const getHeight = ({ large }: {| large?: boolean |}) =>
  large ? '60px' : '40px';

export const FormSelect = styled.select`
  && {
    appearance: none;
    background-color: ${getPaletteColor('white')};
    background-image: url(${getChevronDownDataUri});
    background-position: right center;
    background-repeat: no-repeat;
    border-radius: 6px;
    border: 1px solid ${getPaletteColor('greyscale-light')};
    color: ${getForegroundColor};
    font-family: ${getForegroundFont};
    font-size: ${getFormSelectFontSize};
    font-weight: ${getFormSelectFontWeight};
    height: ${getHeight};
    padding: 0 40px 0 20px;
    width: 100%;
    ${getBaseFocusState({ hoverTransition: false, activeTransition: false })}
  }

  ${FOCUS_VISIBLE_SELECTOR} {
    border: 1px solid ${getPaletteColor('greyscale-dark')};
  }

  /* stylelint-disable property-no-vendor-prefix  */
  &:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 50px transparent inset;
    -webkit-text-fill-color: ${getForegroundColor};
  }

  &:-webkit-autofill:focus {
    -webkit-box-shadow: 0 0 0 50px transparent inset;
    -webkit-text-fill-color: ${getForegroundColor};
  }
  /* stylelint-enable */

  &:not([disabled]):hover {
    border: 1px solid ${getPaletteColor('greyscale-medium')};
  }
`;
