import {
  CancelAndCompleteAction,
  CancelationModal,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import React from 'react';
import styled from 'styled-components';
import { useCurrentAction, useOrderId } from '../../../store';
import { ApiResponse } from '../../../types';
import { notification } from 'antd';
import { useClientPortal } from '../../../../store';
interface IProps {
  callOrderAlertsApi: any;
  callOrdersApi?: any;
  callUnresolvedTaskApi?: any;
  callOrderStatusApi: any;
}

const UnholdOrder = (props: IProps) => {
  const [orderId] = useOrderId();
  const [, setCurrentAction] = useCurrentAction();
  const [isClientPortal] = useClientPortal();

  const { fetchData: fetchUnholdData } = useAxios<{
    data: ApiResponse[];
  }>({
    // remove the date from the params as requested by backend
    endpoint: `orders/${orderId}/unhold/`,
    method: 'POST',
  });

  const saveButton = async () => {
    if (orderId) {
      const response = (await fetchUnholdData()) as {
        code: number | null;
        error?: string | null | undefined;
        [key: string]: any;
      };
      if (response?.code === 200) {
        notification.success({
          message: 'Success',
          description: `${response.message}`,
        });
        // call orders api to update status
        if (isClientPortal) {
          await props?.callUnresolvedTaskApi();
        }
        await props?.callOrderAlertsApi();
        await props?.callOrdersApi();
        await props?.callOrderStatusApi();
      }
      if (response?.code !== 200) {
        notification.error({
          message: 'Error',
          description: `${response.error}`,
        });
        setCurrentAction(undefined);
      }
    }
  };

  const closeModal = () => {
    setCurrentAction(undefined);
  };
  return (
    <CancelationModal
      title="Unhold Order"
      description="Are you sure, you want to UnHold the Order?"
      actions={
        <CustomCancelAndCompleteAction
          cancelLabel="Cancel"
          onCancel={closeModal}
          completeLabel="Confirm"
          onComplete={saveButton}
        />
      }
    />
  );
};

const CustomCancelAndCompleteAction = styled(CancelAndCompleteAction)`
  justify-content: center;
`;

export default UnholdOrder;
