'use client'

import { useRouter } from 'next/navigation'
import { useTransition } from 'react'
import { toast } from 'sonner'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { setActiveProductAction } from '@/actions/active-product'

interface Props {
  productId: string
  isDemo: boolean
  /** Navigate here after activation. Omit to refresh the current page in place. */
  redirectTo?: string
  label?: string
}

export function ActivateProductButton({ productId, isDemo, redirectTo, label = 'Activeer' }: Props) {
  const router = useRouter()
  const [isPending, startTransition] = useTransition()

  function handleActivate() {
    startTransition(async () => {
      const result = await setActiveProductAction(productId)
      if (result?.error) toast.error(typeof result.error === 'string' ? result.error : 'Activeren mislukt')
      else if (redirectTo) router.push(redirectTo)
      else router.refresh()
    })
  }

  return (
    <span data-debug-id="activate-product-button" data-debug-label="ActivateProductButton — shared/activate-product-button.tsx">
    <DemoTooltip show={isDemo}>
      <button
        onClick={() => !isDemo && handleActivate()}
        disabled={isDemo || isPending}
        className="text-xs text-primary hover:underline font-medium disabled:opacity-50 disabled:no-underline"
      >
        {label}
      </button>
    </DemoTooltip>
    </span>
  )
}
