import React, { useState } from 'react';
import { useUpdateReturnStatusMutation } from "../../../features/orders/ordersAPI";
import ConfirmModal from '../../../components/common/ConfirmModal';

const ReturnCard = ({ order }) => {
  const [updateReturnStatus] = useUpdateReturnStatusMutation();
  const [modalOpen, setModalOpen] = useState(false);
  const [actionType, setActionType] = useState(null);

  const handleAction = async () => {
    if (!actionType) return;
    await updateReturnStatus({ id: order.id, action: actionType });
    setModalOpen(false);
  };

  return (
    <div className="p-4 border rounded-lg shadow-sm bg-white">
      <h3 className="font-semibold text-lg">Order #{order.orderNumber}</h3>
      <p className="text-gray-600">
        Customer: {order.user?.firstName} {order.user?.lastName}
      </p>
      <p className="text-gray-600">Total: ₹{order.totalAmount}</p>
      <p className="text-gray-600">Status: {order.returnStatus}</p>

      <div className="mt-2 flex gap-2">
        {order.returnStatus === 'REQUESTED' && (
          <>
            <button
              onClick={() => { setActionType('APPROVE'); setModalOpen(true); }}
              className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
            >
              Approve
            </button>
            <button
              onClick={() => { setActionType('REJECT'); setModalOpen(true); }}
              className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
            >
              Reject
            </button>
          </>
        )}
      </div>

      <ConfirmModal
        isOpen={modalOpen}
        title={actionType ? `${actionType} Return Request` : ''}
        message={actionType ? `Are you sure you want to ${actionType.toLowerCase()} this return request?` : ''}
        onCancel={() => setModalOpen(false)}
        onConfirm={handleAction}
      />
    </div>
  );
};

export default ReturnCard;
