import { makeStyles } from "@material-ui/core/styles";
import {
  SimpleForm,
  TextInput,
  BooleanInput,
  DateInput,
  Edit,
  Toolbar,
  SaveButton,
  DeleteButton,
  EditProps,
  useRedirect,
} from "react-admin";
import { useSession } from "next-auth/react";
import { UserRoleInput } from "./shared";

const useStyles = makeStyles((_theme) => ({
  defaultToolbar: {
    flex: 1,
    display: "flex",
    justifyContent: "space-between",
  },
}));

const UserEditToolbar = (props) => {
  const classes = useStyles(props);
  const redirect = useRedirect();

  return (
    <Toolbar className={classes.defaultToolbar} {...props}>
      <SaveButton
        label="save"
        mutationOptions={{ onSuccess: (response) => redirect("/users") }}
      />
      <DeleteButton disabled={props.session.user.id === props.record.id} />
    </Toolbar>
  );
};

const UserTitle = ({ record }: { record?: any }) => {
  let title = "";
  if (record) title = record.name ? record.name : record.email;
  return <span>User {title}</span>;
};

const UserEdit = (props: EditProps) => {
  const { data: session } = useSession();

  return (
    <Edit title={<UserTitle />} {...props}>
      <SimpleForm toolbar={<UserEditToolbar session={session} />}>
        <TextInput disabled source="id" />
        <TextInput source="email" />
        <TextInput source="name" />
        <UserRoleInput session={session} />
        <DateInput source="emailVerified" />
        <BooleanInput source="isActive" />
        <TextInput source="createdBy" />
      </SimpleForm>
    </Edit>
  );
};

export default UserEdit;
