import * as React from 'react';
import OutlinedInput from '@mui/material/OutlinedInput';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import ListItemText from '@mui/material/ListItemText';
import Select from '@mui/material/Select';
import Checkbox from '@mui/material/Checkbox';

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

export default function CheckMarks({rows, name, filterValue, handleChange, filterName, width, nonMulti, nullValue, identity}) {
    const realValue = !nonMulti ? filterValue.filter((v) => v.length > 0) : filterValue;
    return (
        <div>
            <FormControl sx={{m: 1, width: !width ? 300 : width}}>
                <InputLabel>{name}</InputLabel>
                <Select
                    multiple={!nonMulti}
                    value={realValue}
                    onChange={(e) => handleChange(filterName, e.target.value)}
                    input={<OutlinedInput label={name}/>}
                    renderValue={(selected) => !nonMulti ? selected.join(", ") : selected}
                    MenuProps={MenuProps}
                    defaultChecked={nonMulti && rows[0]}
                    variant="filled">
                    {(nonMulti && nullValue) && (
                        <MenuItem value={""}>
                            <em>Не выбрано</em>
                        </MenuItem>
                    )}
                    {rows.map((value) => {
                        if(identity) {
                            return (
                                <MenuItem key={"menuItemIn" + value} value={value}>
                                    {!nonMulti && (
                                        <Checkbox
                                            checked={realValue.includes(value)}/>
                                    )}
                                    <ListItemText primary={value}/>
                                </MenuItem>
                            )
                        } else {
                            return (
                                <MenuItem key={value.id} value={value.name}>
                                    {!nonMulti && (
                                        <Checkbox
                                            checked={realValue.includes(value.name)}/>
                                    )}
                                    <ListItemText primary={value.name}/>
                                </MenuItem>
                            )
                        }
                    })}
                </Select>
            </FormControl>
        </div>
    );
}