import { getClassNames } from '@websolutespa/bom-core';
import { ComponentPropsWithRef, forwardRef, SVGProps } from 'react';
import styled from 'styled-components';
import { UIComponentWithRef, UIStyledComponentProps } from '../../components/types';
import { getCssResponsive } from '../../components/utils';
import { FormControlCss } from '../styles';
import { SelectLegacyIcon } from './select-legacy-icon';

type Props = ComponentPropsWithRef<'select'> & {
};

export type SelectLegacyProps = UIStyledComponentProps<Props, 'select'>;

export type SelectLegacyComponent<C extends React.ElementType = 'select'> = UIComponentWithRef<C, Props>;

const DownArrowSvg = (props: SVGProps<SVGSVGElement>) => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <polyline points="6 9 12 15 18 9"></polyline>
  </svg>
);

const DownArrow = styled(DownArrowSvg)`
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  margin-left: -2.8rem;
  align-self: center;
  pointer-events: none;
`;

const StyledSelect = styled.div`
  ${FormControlCss}

  display: block;
  width: 100%;
  padding: var(--form-control-padding);
  appearance: none;
  cursor: pointer;

  .icon {
    pointer-events: none;
    transition: color 200ms ease, transform 200ms ease;
  }

  &.opened {
    .icon {
      transform: rotate(180deg);
    }
  }

  ${props => getCssResponsive(props)}
`;

const StyledWrapper = styled.div`
  display: flex;
  align-items: center;
  ${props => getCssResponsive(props)}
`;

export const SelectLegacy: SelectLegacyComponent = forwardRef(({
  as = 'select',
  className,
  ...props
}, ref) => {
  const classNames = getClassNames('select', className);
  return (
    <StyledWrapper className={classNames}>
      <StyledSelect ref={ref} as={as} {...props} />
      <SelectLegacyIcon />
    </StyledWrapper>
  );
});

SelectLegacy.displayName = 'SelectLegacy';
