"use client";

import { useState } from "react";
import { useMutation } from "convex/react";
import { useRouter } from "next/navigation";
import { api } from "../../../../../convex/_generated/api";
import type { Id } from "../../../../../convex/_generated/dataModel";
import type { OrderLineItem } from "./types";

export function useOrderActions(): {
  cancelOrder: (orderId: string) => Promise<{ success: boolean }>;
  isCancelling: boolean;
  requestReturn: (orderId: string) => Promise<{ success: boolean }>;
  isRequestingReturn: boolean;
  reorderItems: (
    items: OrderLineItem[],
    sessionId?: string,
  ) => Promise<{ added: number; skipped: number }>;
  isReordering: boolean;
} {
  const [isCancelling, setIsCancelling] = useState(false);
  const [isRequestingReturn, setIsRequestingReturn] = useState(false);
  const [isReordering, setIsReordering] = useState(false);

  const cancelMutation = useMutation(api.orders.cancel);
  const requestReturnMutation = useMutation(api.orders.requestReturn);
  const addItemMutation = useMutation(api.carts.addItem);
  const router = useRouter();

  async function cancelOrder(orderId: string): Promise<{ success: boolean }> {
    setIsCancelling(true);
    try {
      await cancelMutation({ id: orderId as Id<"orders"> });
      return { success: true };
    } catch {
      return { success: false };
    } finally {
      setIsCancelling(false);
    }
  }

  async function requestReturn(orderId: string): Promise<{ success: boolean }> {
    setIsRequestingReturn(true);
    try {
      await requestReturnMutation({ id: orderId as Id<"orders"> });
      return { success: true };
    } catch {
      return { success: false };
    } finally {
      setIsRequestingReturn(false);
    }
  }

  async function reorderItems(
    items: OrderLineItem[],
    sessionId?: string,
  ): Promise<{ added: number; skipped: number }> {
    setIsReordering(true);
    let added = 0;
    let skipped = 0;
    try {
      for (const item of items) {
        try {
          await addItemMutation({
            variantId: item.variantId as Id<"productVariants">,
            quantity: item.quantity,
            sessionId,
          });
          added++;
        } catch {
          // Item is no longer available — skip silently
          skipped++;
        }
      }
    } finally {
      setIsReordering(false);
    }
    router.push("/cart");
    return { added, skipped };
  }

  return { cancelOrder, isCancelling, requestReturn, isRequestingReturn, reorderItems, isReordering };
}
