'use client'

import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'

export default function AdminDealerDelete({ id }: { id: number }) {
  const router = useRouter()
  const [pending, start] = useTransition()
  const [error, setError] = useState<string | null>(null)

  function handleDelete() {
    if (!confirm('Bu bayiyi silmek istediğinize emin misiniz?')) return
    start(async () => {
      setError(null)
      try {
        const res = await fetch(`/api/admin/dealers/${id}`, { method: 'DELETE' })
        if (res.ok) {
          router.refresh()
          return
        }
        const d = await res.json().catch(() => ({}))
        setError(d.error ?? 'Silme başarısız.')
      } catch {
        setError('Bir hata oluştu.')
      }
    })
  }

  return (
    <div className="flex flex-col items-start gap-1">
      <button
        onClick={handleDelete}
        disabled={pending}
        className="px-3 py-1 rounded-lg bg-red-600 text-white font-body text-xs hover:bg-red-700 transition-colors disabled:opacity-50"
      >
        {pending ? 'Siliniyor...' : 'Sil'}
      </button>
      {error && <span className="font-body text-xs text-red-600">{error}</span>}
    </div>
  )
}
