import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { v4 as uuidv4 } from 'uuid';

export interface IOptionsProps {
  id: number;
  value: string;
  option: string | JSX.Element;
}

export interface IDropdownProps {
  options: IOptionsProps[];
  width?: string;
  onChange: (value: string) => void;
  opensUp?: boolean; // Add a new prop to control the dropdown direction
}

export const Dropdown: React.FC<IDropdownProps> = ({
  options,
  width,
  onChange,
  opensUp = false, // Default value is false
}) => {
  const dropdownId = uuidv4();

  const [selectedValue, setSelectedValue] = useState<string>('');
  const [selectedOption, setSelectedOption] = useState<string | JSX.Element>(
    ''
  );
  const [opened, setOpened] = useState<boolean>(false);

  useEffect(() => {
    const firstOption = options[0];

    if (firstOption) {
      let change = !selectedValue;
      if (!change) {
        change = options.filter(o => o.value === selectedValue).length < 1;
      }

      if (change) {
        setSelectedValue(firstOption.value);
        setSelectedOption(firstOption.option);
      }
    }
  }, [options]);

  useEffect(() => {
    if (selectedValue) {
      onChange(selectedValue);
    }
  }, [selectedValue]);

  return (
    <Container onMouseLeave={() => setOpened(false)} width={width}>
      <DropdownSelect
        id={`dropdown-${dropdownId}`}
        className="rpgui-dropdown-imp rpgui-dropdown-imp-header"
        onPointerUp={() => setOpened(prev => !prev)}
      >
        <label>▼</label> {selectedOption}
      </DropdownSelect>

      <DropdownOptions
        className="rpgui-dropdown-imp"
        opened={opened}
        opensUp={opensUp}
      >
        {options.map(option => {
          return (
            <li
              key={option.id}
              onPointerUp={() => {
                setSelectedValue(option.value);
                setSelectedOption(option.option);
                setOpened(false);
              }}
            >
              {option.option}
            </li>
          );
        })}
      </DropdownOptions>
    </Container>
  );
};

const Container = styled.div<{ width: string | undefined }>`
  position: relative;
  width: ${props => props.width || '100%'};
`;

const DropdownSelect = styled.p`
  width: 100%;
  box-sizing: border-box;

  label {
    display: inline-block;
    transform: translateY(-2px);
  }
`;

const DropdownOptions = styled.ul<{
  opened: boolean;
  opensUp: boolean;
}>`
  position: absolute;
  width: 100%;
  max-height: 300px;
  overflow-y: auto;
  display: ${props => (props.opened ? 'block' : 'none')};
  box-sizing: border-box;
  bottom: ${props => (props.opensUp ? '100%' : 'auto')};
  top: ${props => (props.opensUp ? 'auto' : '100%')};
  margin: 0;
  padding: 0;
  @media (max-width: 768px) {
    padding: 8px 0;
  }
`;
