import { FC } from "react";
import { makeStyles } from "@mui/material/styles";
import {
  SimpleForm,
  TextInput,
  Edit,
  ReferenceInput,
  SelectInput,
  DateInput,
  Toolbar,
  DeleteButton,
  EditProps,
} from "react-admin";
import { useSession } from "next-auth/react";

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

type AccountEditToolbarProps = {
  record?: any;
};

const AccountEditToolbar: FC<AccountEditToolbarProps> = (props: any) => {
  const { data: session } = useSession();
  // @ts-expect-error
  const classes = useStyles(props);
  return (
    <Toolbar className={classes.defaultToolbar} {...props}>
      <DeleteButton disabled={session?.user?.email === props.record?.userId} />
    </Toolbar>
  );
};

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

export const AccountEdit = (props: EditProps) => (
  <Edit title={<AccountTitle />} {...props}>
    <SimpleForm toolbar={<AccountEditToolbar />}>
      <TextInput disabled source="id" />
      <ReferenceInput source="userId" reference="users">
        <SelectInput disabled optionText="email" />
      </ReferenceInput>
      <TextInput disabled source="providerType" />
      <TextInput disabled source="providerId" />
      <TextInput disabled source="providerAccountId" />
      <DateInput disabled source="createdAt" />
      <DateInput disabled source="updatedAt" />
    </SimpleForm>
  </Edit>
);
export default AccountEdit;
