import {
  CancelAndCompleteAction,
  CancelationModal,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import React from 'react';
import styled from 'styled-components';
import {
  useCurrentAction,
  useGlobalStateHitAuditLog,
  useGlobalStateHitOrder,
  useOrderDetails,
} from '../../../store';
import { notification } from 'antd';
import { ApiResponse } from '../../../types';

function OrderLock() {
  const [, setCurrentAction] = useCurrentAction();
  const [orderDetails, setOrderdetails] = useOrderDetails();
  const [, setRecallOrders] = useGlobalStateHitOrder();
  const [, setRecallAuditLog] = useGlobalStateHitAuditLog();

  //update order
  const { fetchData: callUpdateOrderAPI } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/orders/update/`,
    method: 'PUT',
  });

  const title =
    orderDetails?.order_locked === true ? 'Unlocking Order' : 'Locking Order';
  const action = orderDetails?.order_locked === true ? 'Unlock' : 'Lock';

  const onClose = () => {
    setCurrentAction(undefined);
  };

  const onComplete = async () => {
    setRecallOrders(false);
    const isLocked =
      orderDetails?.order_locked === null ? false : orderDetails?.order_locked;
    const payload = [{ id: orderDetails?.id, order_locked: !isLocked }];
    try {
      let response = (await callUpdateOrderAPI({
        payload: payload,
      })) as {
        code: number | null;
        error?: string | null | undefined;
        [key: string]: any;
      };
      if (response.code == 200 && response?.data?.length > 0) {
        notification.success({
          message: 'Success',
          description: `${response?.message}`,
        });
        setOrderdetails(response?.data[0]);
        setRecallAuditLog(true);
        setRecallOrders(true);
      } else {
        notification.error({
          message: 'Error',
          description: `${response?.error}`,
        });
      }
    } catch (error) {}
    onClose();
  };
  return (
    <CustomCancelationModal
      title={title}
      description={`Are you sure want to ${action} this order?`}
      actions={
        <CustomCancelAndCompleteAction
          cancelLabel="cancel"
          onCancel={onClose}
          completeLabel="confirm"
          onComplete={onComplete}
        />
      }
    />
  );
}

const CustomCancelationModal = styled(CancelationModal)`
  background: rgba(0, 0, 0, 0.8);
`;

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

export default OrderLock;
