import { KeyboardArrowDown } from '@mui/icons-material'
import {
  BaseSelectProps,
  Box,
  BoxProps,
  FormControl,
  FormHelperText,
  MenuItem,
  Select,
  styled,
} from '@mui/material'
import { ReactNode } from 'react'
import FormLabel from './FormLabel'

const StyledFormControl = styled(FormControl)(({ theme }) => ({
  '& .MuiInputBase-root': {
    '& legend': { display: 'none' },
    '& .MuiSelect-select': {},
    '& .MuiSvgIcon-root': {
      right: '14px',
    },
  },
}))

const PaperProps = {
  elevation: 0,
  sx: {
    borderRadius: '10px',
    borderTopRightRadius: 0,
    borderTopLeftRadius: 0,
    boxShadow: '0px 4px 16px #0000000F',
    maxHeight: 360,
    marginTop: '1px',
    '& .MuiList-root': {
      padding: 0,
      '& li': {
        height: '60px',
        borderBottom: (theme) => theme.borders.grayLight,
        ':hover': {
          backgroundColor: 'rgba(0, 0, 0, 0.025)',
        },
      },
      '& > :last-child': {
        borderBottom: 'none',
      },
    },
  },
}

type Props = {
  options: Array<{ label: ReactNode; value: any }>
  onChange?: (value: any) => void
  required?: boolean
  firstItemEmpty?: boolean
  helperText?: string
  containerProps?: BoxProps
  onOpen?: (e: any) => void
} & BaseSelectProps

export default function SingleSelect({
  name = 'select',
  options = [],
  label,
  onChange,
  required,
  value,
  helperText,
  containerProps,
  firstItemEmpty = false,
  ...props
}: Props) {
  const inputOptions = firstItemEmpty
    ? [{ label: 'All', value: '__empty__' }, ...options]
    : options

  return (
    <Box width="100%" {...containerProps}>
      <FormLabel required={required} label={label} name={name} />
      <StyledFormControl fullWidth>
        <Select
          id={name}
          multiple={false}
          variant="outlined"
          value={value}
          displayEmpty={firstItemEmpty}
          fullWidth
          label={label}
          MenuProps={{
            PaperProps: PaperProps,
          }}
          onOpen={props?.onOpen}
          IconComponent={KeyboardArrowDown}
          onChange={onChange}
          {...props}
        >
          {inputOptions?.map((item, index) => (
            <MenuItem key={index} value={item.value}>
              {item.label}
            </MenuItem>
          ))}
        </Select>
        {helperText && <FormHelperText>{helperText}</FormHelperText>}
      </StyledFormControl>
    </Box>
  )
}
