"use client";

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

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

const UserEditToolbar = (props: any) => {
  const classes: any = {}; // = useStyles();
  const redirect = useRedirect();
  const record = useRecordContext();
  const { session } = props;

  const shouldDisableDelete =
    !session || !session.user || session.user.id === record.id;

  return (
    <Toolbar className={classes.defaultToolbar}>
      <SaveButton
        label="save"
        mutationOptions={{ onSuccess: () => redirect("/users") }}
      />
      <DeleteButton disabled={shouldDisableDelete} />
    </Toolbar>
  );
};

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

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

  return (
    <Edit title={<UserTitle />}>
      <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;
