'use client'

import { useState, useTransition } from 'react'
import { Button } from '@/components/ui/button'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { leaveProductAction } from '@/actions/products'
import { debugProps } from '@/lib/debug'

interface LeaveProductButtonProps {
  productId: string
  isDemo?: boolean
}

export function LeaveProductButton({ productId, isDemo = false }: LeaveProductButtonProps) {
  const [confirming, setConfirming] = useState(false)
  const [isPending, startTransition] = useTransition()

  function handleLeave() {
    startTransition(async () => {
      await leaveProductAction(productId)
    })
  }

  if (confirming) {
    return (
      <div className="flex gap-2 shrink-0" {...debugProps('leave-product-button', 'LeaveProductButton', 'components/settings/leave-product-button.tsx')}>
        <Button variant="destructive" size="sm" disabled={isPending} onClick={handleLeave}>
          {isPending ? 'Bezig…' : 'Ja, verlaten'}
        </Button>
        <Button variant="ghost" size="sm" onClick={() => setConfirming(false)} disabled={isPending}>
          Annuleren
        </Button>
      </div>
    )
  }

  return (
    <span {...debugProps('leave-product-button', 'LeaveProductButton', 'components/settings/leave-product-button.tsx')}>
      <DemoTooltip show={isDemo}>
        <Button
          variant="outline"
          size="sm"
          className="shrink-0 border-error/40 text-error hover:bg-error/10"
          disabled={isDemo}
          onClick={() => !isDemo && setConfirming(true)}
        >
          Verlaten
        </Button>
      </DemoTooltip>
    </span>
  )
}
