// @flow
import styled from 'styled-components';
import { getPaletteColor } from '../../../mixins/branding';
import { getFontFamily, getFontSize } from '../../../mixins/typography';
import { getCardBorderRadius } from '../internals/forms.css-rules';
import { floatingLabelInputStyles } from '../internals/forms.common';

const getForegroundColor = ({ theme, error, disabled, isPlaceholderValue }) => {
  if (disabled) return getPaletteColor('greyscale-dark')({ theme });
  if (error) return getPaletteColor('error-fg')({ theme });
  if (isPlaceholderValue) {
    return getPaletteColor('greyscale-dark')({ theme });
  }

  return getPaletteColor(theme.defaultTextColor || 'greyscale-black')({
    theme,
  });
};

const getFormSelectFontWeight = ({ isPlaceholderValue, labelStyle }) =>
  isPlaceholderValue || labelStyle === 'external' ? 'normal' : 'bold';

const getFormSelectFontStyle = ({ isPlaceholderValue }) =>
  isPlaceholderValue ? 'italic' : undefined;

const getSelectPaddingVertical = ({ theme, labelStyle }) =>
  labelStyle === 'floating' || labelStyle === 'external-large'
    ? theme.spacing.s2
    : theme.spacing.s1;

const getSelectPaddingRight = ({ theme }) => theme.spacing.s1;
const getSelectPaddingLeft = ({ theme }) => theme.spacing.s2;

// Setting the height as fontSize plus vertical padding allows consistent
// label float calculations with varying fontSize. We could do this more
// simply by setting margins instead of padding, but then the click hotspot
// for the internal DOM input is too small.
const getHeight = (props) =>
  `${
    Number.parseInt(getFontSize(props), 10) +
    Number.parseInt(getSelectPaddingVertical(props), 10) * 2
  }px`;

export const FormSelect = styled.select`
  && {
    appearance: none;
    border: 0;
    display: block;
    outline: none;
    border-radius: ${getCardBorderRadius};
    color: ${getForegroundColor};
    font-family: ${getFontFamily};
    font-size: ${getFontSize};
    font-weight: ${getFormSelectFontWeight};
    font-style: ${getFormSelectFontStyle};
    width: 100%;
    padding-top: ${getSelectPaddingVertical};
    padding-right: ${getSelectPaddingRight};
    padding-bottom: ${getSelectPaddingVertical};
    padding-left: ${getSelectPaddingLeft};
    height: ${getHeight};
    line-height: 1;
    opacity: 0;
    transform: none;
    overflow: hidden;
    background: transparent;

    ${floatingLabelInputStyles}
  }

  /* 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 */

  option {
    font-weight: 100;
    font-style: normal;
    color: ${getPaletteColor('greyscale-dark')};
  }
`;
