import {
  BooleanField,
  BooleanInput,
  CoverField,
  Datagrid,
  DateField,
  EmailField,
  FunctionField,
  ImpersonateUserButton,
  List,
  SearchInput,
  SelectInput,
  SimpleList,
  TextField
} from '@applica-software-guru/react-admin';
import { Chip, useMediaQuery } from '@mui/material';

function sortRoles(userRoles, roles) {
  return userRoles
    ?.filter((r) => roles.find((cr) => cr.id === r))
    .sort((a, b) => {
      const aIndex = roles.findIndex((r) => r.id === a);
      const bIndex = roles.findIndex((r) => r.id === b);

      return aIndex - bIndex;
    });
}

function RolesInput({ record, source, roles, ...props }) {
  return (
    <SelectInput
      source={source}
      choices={roles}
      format={(v) => v}
      parse={(v) => v}
      alwaysOn
      emptyText="ra.action.view_all"
      display="legend"
      {...props}
    />
  );
}

function ImageField(record) {
  return <CoverField source="image" record={record} width={50} height={50} circle />;
}

function NameField(record) {
  return record.name;
}

function SecondaryField(record) {
  return record.email;
}

function UserList({ roles }) {
  const isSmall = useMediaQuery((theme) => theme.breakpoints.down('sm'));
  return (
    <List
      perPage={25}
      filters={[
        <SearchInput key="keyword" source="keyword" alwaysOn fullWidth />,
        <RolesInput key="role" source="role" choices={roles} />,
        <BooleanInput key="active" source="active" display="legend" />
      ]}
    >
      {isSmall ? (
        <SimpleList leftAvatar={ImageField} primaryText={NameField} secondaryText={SecondaryField} />
      ) : (
        <Datagrid rowClick="edit">
          <CoverField source="image" sortable={false} label="" width={50} height={50} circle />
          <BooleanField source="active" />
          <TextField source="name" sortBy="username" />
          <EmailField source="email" />
          <DateField source="registrationDate" showTime />
          <ImpersonateUserButton />
        </Datagrid>
      )}
    </List>
  );
}

export { UserList };
