'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'
import { debugProps } from '@/lib/debug'

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 {...debugProps('activate-product-button')}>
    <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>
  )
}
