import {
  FormControl,
  MenuItem,
  Select as SelectMui,
  SelectChangeEvent,
  styled,
  SelectProps as SelectMuiProps,
  MenuItemProps
} from '@mui/material'

const SelectCustomized = styled(SelectMui)<SelectMuiProps>(() => ({
  backgroundColor: 'var(--primary-main)',
  fontSize: '14px',
  fontWeight: '500',
  color: 'white',
  ':hover': {
    backgroundColor: 'var(--primary-light)'
  },
  '& .MuiSelect-select:focus': {
    backgroundColor: 'var(--primary-light)'
  },
  '& .MuiSvgIcon-root': {
    color: 'white'
  },
  '& .MuiOutlinedInput-notchedOutline': {
    border: 'none'
  }
}))

const MenuItemCustomized = styled(MenuItem)<MenuItemProps>(() => ({
  marginInline: '5px',
  borderRadius: '4px',
  '&:hover': {
    background: 'var(--primary-light)',
    color: 'white'
  },
  '&.Mui-selected': {
    background: 'var(--primary-dark)',
    color: 'white'
  },
  '&.Mui-selected:hover': {
    background: 'var(--primary-light)'
  },
  '&.Mui-selected.Mui-focusVisible': {
    background: 'var(--primary-light)',
    color: 'white'
  },
  '&.Mui-focusVisible': {
    background: 'var(--primary-light)',
    color: 'white'
  },
  '& + *': {
    marginTop: '5px'
  }
}))

interface SelectItemProps<T extends string> {
  value: T
  label: string
}

interface SelectProps<T extends string> {
  setValue: React.Dispatch<React.SetStateAction<T>>
  options: SelectItemProps<T>[]
  name?: string
  id?: string
}

export function Select<T extends string>({
  setValue,
  options,
  name,
  id
}: SelectProps<T>) {
  const handleChange = (event: SelectChangeEvent<unknown>) => {
    setValue(event.target.value as T)
  }

  return (
    <FormControl>
      <SelectCustomized
        id={id}
        name={name}
        size="small"
        variant="outlined"
        defaultValue={options[0].value as string}
        onChange={handleChange}
        MenuProps={{
          MenuListProps: {
            sx: {
              paddingBlock: '5px'
            }
          },
          PaperProps: {
            sx: {
              boxShadow: '0 0 4px 0 rgb(0, 0, 0, 0.1)'
            }
          }
        }}
      >
        {options.map((o) => {
          return (
            <MenuItemCustomized key={o.label} value={o.value as string}>
              {o.label}
            </MenuItemCustomized>
          )
        })}
      </SelectCustomized>
    </FormControl>
  )
}
