import React, { useState } from 'react';
import styled from 'styled-components';

import v from '../../styles/Variables';

// theme for default styles, addon like cart {jsx}, shadow?

interface Props {
  /**
   * valid hex/rgba color for the background
   */
  background?: string;
  /**
   * callback function when the button is clicked
   */
  callback: (p: string, q: string) => void;
  /**
   * font color to be used, can be hex, rgba, or a variable
   */
  color?: string;
  /**
   * the text of the button or selected item
   */
  dropTitle: string;
  /**
   * dropdown width in pixels
   */
  dropdownWidth?: number;
  /**
   * font size in pixels
   */
  fontSize?: number;
  /**
   * if  the button should be inline-block or block
   */
  fullWidth?: boolean;
  /**
   * padding applied to all 4 sides, in pixels, as a string (valid css)
   */
  padding?: string;
  /**
   * the rounding amount of the button
   */
  radius?: 'rounded' | 'square' | 'pill';
  /**
   * id of the element
   */
  id?: string;
  /**
   * the list options of the button
   */
  options?: Array<Options>;
  /**
   * If using our variables, any valid color variable, or default, dark, none
   */
  theme?: string;
  /**
   * extra classes to be applied
   */
  themeClass?: string;
  /**
   * show Chevron on the left side of the dropdown
   */
  onLeftChevron?: boolean;
  /**
   * left position to be applied for the Chevron. use it along with onLeftChevron
   */
  chevronPositionLeft?: string;
  /**
   * right position to be applied for the Chevron. use it for the default right chevron.
   */
  chevronPositionRight?: string;
  /**
   * top position to be applied for the Chevron.
   */
  chevronPositionTop?: string;
}

interface Options {
  title: string;
  value: string;
  bottomTitle: string;
  showBottomTitle: boolean;
}

interface DropdownBtnStyle {
  background: string;
  color: string;
  fontSize: number;
  fullWidth: boolean;
  padding: string;
  radius: 'rounded' | 'pill' | 'square';
  theme: string;
  isHidden?: boolean;
  onLeftChevron?: boolean;
}

interface AngleDownLeftStyle {
  chevronPositionLeft?: string;
  chevronPositionTop?: string;
}
interface AngleDownRightStyle {
  chevronPositionRight?: string;
  chevronPositionTop?: string;
}
interface DropdownWrapStyle {
  fullWidth: boolean;
}

interface DropdownContentStyle {
  dropdownWidth: number;
  isHidden: boolean;
  children: React.ReactNode;
  fullWidth: boolean;
}

const Dropdown = ({
  background = v.colors.light,
  callback,
  color = v.colors.dark,
  dropTitle,
  dropdownWidth = 160,
  fontSize = 14,
  fullWidth = false,
  id = 'dropdown',
  options = [
    { title: 'Dropdown here', value: '0', bottomTitle: 'Bottom title here', showBottomTitle: true },
    { title: 'Dropdown here', value: '1', bottomTitle: 'Bottom title here', showBottomTitle: false },
  ],
  padding = '10px 40px',
  radius = 'rounded',
  theme = 'default',
  themeClass,
  onLeftChevron = false,
  chevronPositionLeft,
  chevronPositionRight,
  chevronPositionTop,
}: Props) => {
  const [isHidden, setIsHidden] = useState(true);
  return (
    <DropdownWrapper fullWidth={fullWidth} className={`nwc--buttonWrapper ${themeClass}`}>
      <DropdownBtn
        aria-expanded={isHidden === false ? 'true' : 'false'}
        onBlur={() => {
          setTimeout(() => {
            setIsHidden(true);
          }, 200);
        }}
        onClick={() => {
          setTimeout(() => {
            setIsHidden(!isHidden);
          }, 200);
        }}
        className={`nwc--button`}
        background={background}
        color={color}
        fontSize={fontSize}
        fullWidth={fullWidth}
        padding={padding}
        radius={radius}
        isHidden={isHidden}
        theme={theme}
        id={id}
        aria-controls={`${id}--content`}
      >
        {dropTitle}
        {onLeftChevron && (
          <AngleDownLeft chevronPositionLeft={chevronPositionLeft} chevronPositionTop={chevronPositionTop}>
            <i className="fal fa-chevron-down" aria-hidden="true" />
          </AngleDownLeft>
        )}
        {!onLeftChevron && (
          <AngleDownRight chevronPositionRight={chevronPositionRight} chevronPositionTop={chevronPositionTop}>
            <i className="fal fa-chevron-down" aria-hidden="true" />
          </AngleDownRight>
        )}
      </DropdownBtn>
      <DropdownContent id={`${id}--content`} isHidden={isHidden} dropdownWidth={dropdownWidth} fullWidth={fullWidth}>
        {isHidden === false &&
          options &&
          options.length > 0 &&
          options.map((option, i) => (
            <DropdownItem
              key={i}
              onClick={() => {
                callback(option.title, option.value);

                setTimeout(() => {
                  setIsHidden(!isHidden);
                }, 200);
              }}
            >
              {option.title}
              {option.showBottomTitle === true && (
                <span>
                  <br />
                  <small>{option.bottomTitle}</small>
                </span>
              )}
            </DropdownItem>
          ))}
      </DropdownContent>
    </DropdownWrapper>
  );
};

export default Dropdown;

const radiusSwitch = (type: string): string => {
  switch (type) {
    case 'square':
      return '0px';
    case 'rounded':
      return '4px';
    case 'pill':
      return '300px';
    default:
      return '0px';
  }
};

const handleTheme = (theme: string) => {
  // if it's just the none theme, send it right back
  if (theme === 'none') return 'color: #000; border-color: #000; background-color: #fff';

  // @ts-ignore
  const colorTheme: string = v.colors[theme];
  // dynamically look for a color in our variables to style it
  if (theme && colorTheme !== undefined) {
    // check if it's light or dark
    if (['border', 'light', 'offLight', 'placeholder'].indexOf(theme) >= 0) {
      return `color: #000; background: ${colorTheme}; border-color: ${colorTheme}}`;
    } else {
      return `color: #fff; background: ${colorTheme}; border-color: ${colorTheme}}`;
    }
  } else {
    // if not found or not matching, just silently fail
    return null;
  }
};

/* styles */
const DropdownBtn = styled.button<DropdownBtnStyle>`
  background: ${({ background }) => background};
  border: 1px solid ${v.colors.border};
  border-radius: ${({ radius }) => radiusSwitch(radius)};
  color: ${({ color }) => color};
  display: ${({ fullWidth }) => (fullWidth ? 'block' : 'inline-block')};
  font-size: ${({ fontSize }) => `${fontSize}px`};
  padding: ${({ padding }) => padding};
  width: ${({ fullWidth }) => (fullWidth ? '100%' : 'inherit')};
  ${({ theme }) => handleTheme(theme)};
  position: relative;
`;
const DropdownWrapper = styled.div<DropdownWrapStyle>`
  position: relative;
  display: ${({ fullWidth }) => (fullWidth ? 'block' : 'inline-block')};
`;
const AngleDownRight = styled.div<AngleDownRightStyle>`
  position: absolute;
  right: ${({ chevronPositionRight }) => (chevronPositionRight ? chevronPositionRight : '10px')};
  top: ${({ chevronPositionTop }) => (chevronPositionTop ? chevronPositionTop : '30%')};
`;
const AngleDownLeft = styled.div<AngleDownLeftStyle>`
  position: absolute;
  left: ${({ chevronPositionLeft }) => (chevronPositionLeft ? chevronPositionLeft : '10px')};
  top: ${({ chevronPositionTop }) => (chevronPositionTop ? chevronPositionTop : '30%')};
`;

const DropdownContent = styled.div<DropdownContentStyle>`
  position: absolute;
  width: ${({ fullWidth }) => (fullWidth ? '100%' : 'inherit')};
  display: ${({ isHidden }) => (isHidden === false ? 'block' : 'none')};
  background-color: #fff;
  min-width: ${({ dropdownWidth }) => `${dropdownWidth}px`};
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.275);
  z-index: 1;
  margin-top: 5px;
  font-size: 14px;
  z-index: 999;
  right: 0;
  max-height: 150px;
  overflow-y: scroll;
`;
const DropdownItem = styled.div`
  height: 45px;
  padding: 5px 10px;
  cursor: pointer;
  display: block;

  &:hover {
    background-color: #f7f7f7;
  }
`;
