import { HTTPSTATUS } from '@/constants';
import { apiConfirmAlarm } from '@/services/master/AlarmController';
import { CheckOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProForm,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Flex } from 'antd';
import { MessageInstance } from 'antd/es/message/interface';
import moment from 'moment';
import React, { useRef } from 'react';

type AlarmForm = {
  name: string;
  time: string;
  description: string;
};
type AlarmFormConfirmProps = {
  isOpen: boolean;
  setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
  trigger?: React.ReactNode;
  alarm: MasterModel.Alarm;
  message: MessageInstance;
  onFinish?: (reload: boolean) => void;
};
const AlarmFormConfirm = ({
  isOpen,
  setIsOpen,
  trigger,
  alarm,
  message,
  onFinish,
}: AlarmFormConfirmProps) => {
  const formRef = useRef<ProFormInstance<AlarmForm>>();
  const intl = useIntl();
  return (
    <ModalForm<AlarmForm>
      open={isOpen}
      formRef={formRef}
      title={
        <Flex align="center" justify="center">
          <FormattedMessage id="master.alarms.confirm.title" />
        </Flex>
      }
      width="40%"
      layout="horizontal"
      modalProps={{
        destroyOnHidden: true,
        // maskStyle: { backgroundColor: 'rgba(0,0,0,0.1)' },
      }}
      onOpenChange={setIsOpen}
      request={async () => {
        return {
          name: alarm.name ?? '',
          time: moment.unix(alarm.time!).format('DD/MM/YYYY HH:mm:ss'),
          description: alarm.confirmed_desc ?? '',
        };
      }}
      onFinish={async (values) => {
        const body: MasterModel.ConfirmAlarmRequest = {
          id: alarm.id,
          description: values.description,
          thing_id: alarm.thing_id,
          time: alarm.time,
        };
        try {
          const resp = await apiConfirmAlarm(body);
          if (resp.status === HTTPSTATUS.HTTP_ACCEPTED) {
            message.success({
              content: intl.formatMessage({
                id: 'master.alarms.confirm.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 confirm alarm: ', error);
          message.error({
            content: intl.formatMessage({
              id: 'master.alarms.confirm.fail',
              defaultMessage: 'Confirm alarm failed',
            }),
          });
        }

        return true;
      }}
      trigger={
        React.isValidElement(trigger) ? (
          trigger
        ) : (
          <Button
            size="small"
            type="primary"
            icon={<CheckOutlined />}
            onClick={() => setIsOpen(true)}
          >
            {intl.formatMessage({
              id: 'common.confirm',
            })}
          </Button>
        )
      }
    >
      <ProForm.Group>
        <ProFormText
          name="name"
          label={intl.formatMessage({
            id: 'common.name',
            defaultMessage: 'Name',
          })}
          readonly={true}
        />
        <ProFormText
          name="time"
          label={intl.formatMessage({
            id: 'master.alarms.occurred_at',
            defaultMessage: 'When',
          })}
          readonly={true}
        />
      </ProForm.Group>
      <ProFormText
        fieldProps={{
          autoFocus: true,
        }}
        name="description"
        label={intl.formatMessage({
          id: 'common.description',
          defaultMessage: 'Description',
        })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'master.alarms.confirm.description.required',
              defaultMessage: 'The description is required',
            }),
          },
        ]}
      />
    </ModalForm>
  );
};

export default AlarmFormConfirm;
