import { FC, memo } from 'react';

import Box from '@material-hu/mui/Box';
import Checkbox from '@material-hu/mui/Checkbox';
import Container from '@material-hu/mui/Container';
import FormControlLabel from '@material-hu/mui/FormControlLabel';
import FormGroup from '@material-hu/mui/FormGroup';

import { User } from 'src/types/user';

import { PeopleList } from 'src/components/dashboard/people/PeopleList';

export type PeopleListCustomProps = {
  query: string;
  users: any;
  setUsers: any;
};

export const PeopleListCustom: FC<PeopleListCustomProps> = props => {
  const { query, users, setUsers } = props;

  const handleChange = (id: number, checked: boolean) => {
    const newUsers = [...users];
    const index = newUsers.indexOf(id);
    const finded = index !== -1;

    if (checked && !finded) {
      newUsers.push(id);
    } else if (!checked && finded) {
      newUsers.splice(index, 1);
    }
    setUsers(newUsers);
  };

  const renderUser = (user: User) => (
    <Box sx={{ ml: 4 }}>
      <FormGroup key={user.id}>
        <FormControlLabel
          control={
            <Checkbox
              checked={users.includes(user.id)}
              onChange={e => handleChange(user.id, e.target.checked)}
            />
          }
          label={`${user.firstName}  ${user.lastName}`}
        />
      </FormGroup>
    </Box>
  );

  return (
    <Container sx={{ height: '300px', p: '0 !important' }}>
      <PeopleList
        listContainerStyle={{ backgroundColor: '#f4f5f7' }}
        listSubHeaderStyle={{ backgroundColor: '#f4f5f7' }}
        limit={10}
        query={query}
        renderUserCustom={renderUser}
      />
    </Container>
  );
};

export default memo(PeopleListCustom);
