import { useEffect } from 'react';
import { Button, ButtonProps } from './Button';
import NotificationsActiveIcon from '@mui/icons-material/NotificationsActive';
import NotificationsOffIcon from '@mui/icons-material/NotificationsOff';
import { PushNotificationConfig, usePushNotifications } from '@/hooks/usePushNotifications';
import { useNotify } from 'ra-core';

interface PushNotificationToggleButtonProps extends Omit<ButtonProps, 'onClick'> {
  config: PushNotificationConfig;
}

function PushNotificationToggleButton({
  config,
  label = 'ra.notification.push',
  ...props
}: PushNotificationToggleButtonProps) {
  const { status, toggle, error } = usePushNotifications(config);
  const notify = useNotify();
  useEffect(() => {
    if (error) {
      notify(error, { type: 'error' });
    }
  }, [error, notify]);

  return (
    <Button
      {...props}
      onClick={toggle}
      disabled={status === 'pending'}
      startIcon={status === 'enabled' ? <NotificationsActiveIcon /> : <NotificationsOffIcon />}
      label={`${label}.${status}`}
    />
  );
}

export { PushNotificationToggleButton };
export type { PushNotificationToggleButtonProps };
