import { HTTPSTATUS } from '@/constants';
import { apiUnconfirmAlarm } from '@/services/master/AlarmController';
import { CloseOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Button, Popconfirm } from 'antd';
import { MessageInstance } from 'antd/es/message/interface';

type AlarmUnConfirmButtonProps = {
  alarm: MasterModel.Alarm;
  onFinish?: (isReload: boolean) => void;
  message: MessageInstance;
  button?: React.ReactNode;
};
const AlarmUnConfirmButton = ({
  alarm,
  message,
  button,
  onFinish,
}: AlarmUnConfirmButtonProps) => {
  const intl = useIntl();
  return (
    <Popconfirm
      title={intl.formatMessage({
        id: 'master.alarms.unconfirm.body',
        defaultMessage: 'Are you sure you want to unconfirm this alarm?',
      })}
      okText={intl.formatMessage({
        id: 'common.yes',
        defaultMessage: 'Yes',
      })}
      cancelText={intl.formatMessage({
        id: 'common.no',
        defaultMessage: 'No',
      })}
      onConfirm={async () => {
        const body: MasterModel.ConfirmAlarmRequest = {
          id: alarm.id,
          thing_id: alarm.thing_id,
          time: alarm.time,
        };
        try {
          const resp = await apiUnconfirmAlarm(body);
          if (resp.status === HTTPSTATUS.HTTP_SUCCESS) {
            message.success({
              content: intl.formatMessage({
                id: 'master.alarms.unconfirm.success',
                defaultMessage: 'Confirm alarm successfully',
              }),
            });
            onFinish?.(true);
          } else if (resp.status === HTTPSTATUS.HTTP_NOTFOUND) {
            message.warning({
              content: intl.formatMessage({
                id: 'master.alarms.not_found',
                defaultMessage: 'Alarm has expired or does not exist',
              }),
            });
            onFinish?.(true);
          } else {
            throw new Error('Failed to confirm alarm');
          }
        } catch (error) {
          console.error('Error when unconfirm alarm: ', error);
          message.error({
            content: intl.formatMessage({
              id: 'master.alarms.unconfirm.fail',
              defaultMessage: 'Unconfirm alarm failed',
            }),
          });
        }
      }}
    >
      {button ? (
        button
      ) : (
        <Button danger icon={<CloseOutlined />} size="small" />
      )}
    </Popconfirm>
  );
};

export default AlarmUnConfirmButton;
