import { useState } from 'react'
import { TrashIcon } from '@heroicons/react/24/outline'

type Props = {
  onDelete: () => Promise<void>
  disabled?: boolean
}

export default function ConfirmDeleteButton({ onDelete, disabled = false }: Props) {
  const [confirming, setConfirming] = useState(false)
  const [deleting, setDeleting] = useState(false)

  async function handleConfirm() {
    setDeleting(true)
    await onDelete()
    // Only reached if onDelete didn't navigate away (e.g. error handled by parent)
    setDeleting(false)
    setConfirming(false)
  }

  if (confirming) {
    return (
      <div className="flex items-center gap-2">
        <span className="text-sm text-stone-500 dark:text-stone-400">Delete?</span>
        <button
          onClick={handleConfirm}
          disabled={deleting}
          className="text-sm font-medium text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 disabled:opacity-50"
        >
          {deleting ? 'Deleting…' : 'Yes'}
        </button>
        <button
          onClick={() => setConfirming(false)}
          disabled={deleting}
          className="text-sm text-stone-500 dark:text-stone-400 hover:text-stone-700 dark:hover:text-stone-200 disabled:opacity-50"
        >
          No
        </button>
      </div>
    )
  }

  return (
    <button
      onClick={() => setConfirming(true)}
      disabled={disabled}
      className="flex items-center gap-1.5 text-sm text-stone-500 dark:text-stone-400 hover:text-red-600 dark:hover:text-red-400 transition-colors"
    >
      <TrashIcon className="size-4" />
      Delete
    </button>
  )
}
