import { getClassNames, withSchema } from '@websolutespa/bom-core';
import React, { forwardRef } from 'react';
import styled from 'styled-components';
import { ThemeProps, UIComponentWithRef, UIStyledComponentProps } from '../../components/types';
import { eachMedia, getCssResponsive } from '../../components/utils';
import { IThemeContainerVariant } from '../../theme';

export type ContainerBaseProps = {
  variant?: IThemeContainerVariant;
};

export type ContainerProps = UIStyledComponentProps<ContainerBaseProps>;

export type ContainerComponent<C extends React.ElementType = 'div'> = UIComponentWithRef<C, ContainerBaseProps>;

export const StyledContainer = styled.div<ContainerProps>`
  width: 100%;
  margin: 0 auto;
  ${props => getContainer(props)}
  ${props => getCssResponsive(props)}
`;

export const ContainerBase: ContainerComponent = forwardRef(({ children, as = 'div', className, ...props }, ref) => {
  return (<StyledContainer ref={ref} as={as} className={getClassNames('container', className)} {...props}>{children}</StyledContainer>);
});

ContainerBase.displayName = 'ContainerBase';

export const ContainerFluid: ContainerComponent = forwardRef(({ children, as = 'div', className, ...props }, ref) => {
  return (<StyledContainer ref={ref} as={as} className={getClassNames('container-fluid', className)} {...props} variant="fluid">{children}</StyledContainer>);
});

ContainerFluid.displayName = 'ContainerFluid';

export const Container = withSchema(
  ContainerBase,
  {
    Fluid: ContainerFluid,
  });

export function getContainer(props: ContainerBaseProps & ThemeProps) {
  const theme = props.theme;
  const variant: IThemeContainerVariant = props.variant || 'default';
  const container = theme.container[variant];
  if (container && container.maxWidth) {
    return eachMedia(props, (key: string) => `max-width: ${container.maxWidth[key]}`);
  } else {
    return '';
  }
}
