"use client";

import { Button, Spinner } from "@heroui/react";
import Link from "next/link";
import { CANCELLABLE_STATUSES, RETURNABLE_STATUSES, ORDERS_PATH } from "@/lib/orders";
import type { OrderDetail } from "@/lib/orders";

interface Props {
  order: OrderDetail;
  onCancel: () => void;
  isCancelling: boolean;
  onRequestReturn: () => void;
  isRequestingReturn: boolean;
  onReorder: () => void;
  isReordering: boolean;
}

const REORDERABLE_STATUSES = ["delivered", "cancelled", "refunded"] as const;

export function OrderActions({
  order,
  onCancel,
  isCancelling,
  onRequestReturn,
  isRequestingReturn,
  onReorder,
  isReordering,
}: Props) {
  const canCancel = (CANCELLABLE_STATUSES as readonly string[]).includes(
    order.status,
  );
  const canRequestReturn =
    (RETURNABLE_STATUSES as readonly string[]).includes(order.status) &&
    !order.returnRequestedAt &&
    order.paymentStatus !== "refunded";
  const canReorder = (REORDERABLE_STATUSES as readonly string[]).includes(
    order.status,
  );

  return (
    <div className="flex w-full flex-col gap-3 md:flex-row md:flex-wrap">
      {canCancel && (
        <Button
          variant="danger"
          className="w-full md:w-auto"
          onPress={onCancel}
          isDisabled={isCancelling}
        >
          {isCancelling ? (
            <>
              <Spinner size="sm" />
              Cancelling…
            </>
          ) : (
            "Cancel Order"
          )}
        </Button>
      )}

      {canRequestReturn && (
        <Button
          variant="outline"
          className="w-full md:w-auto"
          onPress={onRequestReturn}
          isDisabled={isRequestingReturn}
        >
          {isRequestingReturn ? (
            <>
              <Spinner size="sm" />
              Submitting…
            </>
          ) : (
            "Request Return"
          )}
        </Button>
      )}

      {order.returnRequestedAt && order.status === "delivered" && (
        <span className="inline-flex w-full items-center justify-center rounded-md border border-gray-200 px-4 py-2 text-sm font-medium text-gray-500 md:w-auto">
          Return Requested
        </span>
      )}

      {canReorder && (
        <Button
          variant="outline"
          className="w-full md:w-auto"
          onPress={onReorder}
          isDisabled={isReordering}
        >
          {isReordering ? (
            <>
              <Spinner size="sm" />
              Adding to cart…
            </>
          ) : (
            "Reorder"
          )}
        </Button>
      )}

      <Link
        href={ORDERS_PATH}
        className="inline-flex w-full items-center justify-center rounded-md px-4 py-2 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900 md:w-auto"
      >
        ← Back to Orders
      </Link>
    </div>
  );
}
