import { VpnKey } from '@mui/icons-material';
import { useCallback, useState } from 'react';
import { Button, useAuthProvider, useRecordContext } from 'react-admin';

type ImpersonateUserButtonProps = {
  label?: string;
  redirect?: string;
  [x: string]: any; // Allow other props to be passed through
};

function ImpersonateUserButton({
  label = 'ra.auth.sign_in',
  redirect = '/',
  ...props
}: ImpersonateUserButtonProps): JSX.Element {
  const record = useRecordContext();
  const [loading, setLoading] = useState(false);
  const authProvider = useAuthProvider();
  const handleClick = useCallback(
    (e: Event) => {
      e.stopPropagation();
      e.preventDefault();
      setLoading(true);
      authProvider.impersonate(record?.id).then(() => {
        setLoading(false);
        document.location.href = redirect;
      });
    },
    [authProvider, record?.id, redirect]
  );
  return (
    <Button
      disabled={loading || authProvider.impersonate === undefined}
      color="primary"
      variant="text"
      label={label}
      // @ts-ignore
      onClick={handleClick}
      {...props}
    >
      <VpnKey />
    </Button>
  );
}

export { ImpersonateUserButton };
export type { ImpersonateUserButtonProps };
