import { Button } from '@components/common/ui/Button.js';
import React from 'react';
import { toast } from 'react-toastify';

interface MarkDeliveredButtonProps {
  order: {
    orderId: string;
    noShippingRequired: boolean;
    shipmentStatus: {
      code: string;
    };
    shipment: {
      shipmentId: number;
    } | null;
  };
  markDeliveredApi: string;
}

export default function MarkDeliveredButton({
  order: {
    orderId,
    noShippingRequired,
    shipmentStatus: { code },
    shipment
  },
  markDeliveredApi
}: MarkDeliveredButtonProps) {
  if (noShippingRequired || !shipment || code === 'delivered') {
    return null;
  } else {
    return (
      <Button
        variant="default"
        onClick={async () => {
          // Call the updateShipmentApi with the status set to "delivered" using fetch post request, include credentials
          const response = await fetch(markDeliveredApi, {
            method: 'POST',
            credentials: 'include',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ order_id: orderId })
          });
          const data = await response.json();
          // If the response is not ok, throw an error
          if (!data.error) {
            // Reload the page
            window.location.reload();
          } else {
            toast.error(data.error.message);
          }
        }}
      >
        Mark Delivered
      </Button>
    );
  }
}

export const layout = {
  areaId: 'order_actions',
  sortOrder: 10
};

export const query = `
  query Query {
    order(uuid: getContextValue("orderId")) {
      noShippingRequired
      orderId
      shipmentStatus {
        code
      }
      shipment {
        shipmentId
      }
    },
    markDeliveredApi: url(routeId: "markDelivered")
  }
`;
