import React from 'react';
import {
  FormControl,
  InputLabel,
  ListItemText,
  MenuItem,
  Select as MuiSelect,
  OutlinedInput,
} from '@mui/material';
import { SelectBaseProps } from '../interfaces';
import { styled } from '@mui/material/styles';
import { CheckBox } from './CheckBox';

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250,
    },
  },
};

const SelectStyled = styled(MuiSelect)(({ multiple, variant }) => ({
  '& .MuiOutlinedInput-notchedOutline': {
    border: multiple === true ? 'none' : '1px solid #666666 ',
    borderRadius: multiple === true ? 0 : 4,
    borderBottom: '1px solid #666666',
  },
  '& .MuiFormLabel-root': {
    backgroundColor: variant === 'standard' ? '#fff' : 'inherit',
    padding: variant === 'standard' ? '0 5px' : 0,
  },
}));

export const Select = ({ label, onChange, data = [], value = '', multiple = false, ...props }: SelectBaseProps) => {
  return (
    <FormControl fullWidth>
      <InputLabel id={props.id}>{label}</InputLabel>

      {multiple ? (
        <SelectStyled
          labelId={props.id}
          id="demo-simple-select"
          value={value}
          MenuProps={MenuProps}
          input={<OutlinedInput label="Tag" />}
          renderValue={(selected: any) => selected.join(', ')}
          onChange={onChange}
          multiple
          {...props}
        >
          {data &&
            data.map((item, key) => (
              <MenuItem value={item.value} key={key}>
                <CheckBox checked={value.includes(String(item.value))} />
                <ListItemText primary={String(item.label)} />
              </MenuItem>
            ))}
        </SelectStyled>
      ) : (
        <SelectStyled labelId={props.id} id="demo-simple-select" value={value} onChange={onChange} {...props}>
          {data &&
            data.map((item, key) => (
              <MenuItem value={item.value} key={key}>
                <ListItemText primary={String(item.label)} />
              </MenuItem>
            ))}
        </SelectStyled>
      )}
    </FormControl>
  );
};
