"use client"

import { useState } from "react"
import { useAction } from "convex/react"
import { toast } from "sonner"
import { api } from "../../../../../../convex/_generated/api"
import type { Id } from "../../../../../../convex/_generated/dataModel"
import { Button } from "@/components/ui/button"

interface Props {
  orderId: Id<"orders">
}

export function AcceptReturnButton({ orderId }: Props) {
  const [isLoading, setIsLoading] = useState(false)
  const acceptReturn = useAction(api.returnActions.acceptReturn)

  async function handleClick() {
    setIsLoading(true)
    try {
      const result = await acceptReturn({ orderId })
      if (result.success) {
        toast.success(`Return accepted. Tracking: ${result.returnTrackingNumber}`)
      } else {
        toast.error((result as { success: false; code: string; message: string }).message)
      }
    } catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : "Failed to accept return.")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Button onClick={handleClick} disabled={isLoading} variant="outline">
      {isLoading && (
        <svg
          data-icon="inline-start"
          className="animate-spin"
          viewBox="0 0 24 24"
          fill="none"
          aria-hidden="true"
        >
          <circle
            className="opacity-25"
            cx="12"
            cy="12"
            r="10"
            stroke="currentColor"
            strokeWidth="4"
          />
          <path
            className="opacity-75"
            fill="currentColor"
            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
          />
        </svg>
      )}
      {isLoading ? "Accepting…" : "Accept Return"}
    </Button>
  )
}
