import { useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'

interface Props {
  open: boolean
  title: string
  message?: string
  onConfirm: () => void
  onCancel: () => void
}

export default function ConfirmDialog({ open, title, message, onConfirm, onCancel }: Props) {
  const { t } = useTranslation()
  const cancelRef = useRef<HTMLButtonElement>(null)

  useEffect(() => {
    if (open) cancelRef.current?.focus()
  }, [open])

  useEffect(() => {
    if (!open) return
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onCancel()
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [open, onCancel])

  if (!open) return null

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-[100]">
      <div className="bg-az-panel border border-az-border rounded-lg p-4 w-80 shadow-xl">
        <h3 className="text-white font-semibold mb-2">{title}</h3>
        {message && <p className="text-az-text text-sm mb-4">{message}</p>}
        <div className="flex justify-end gap-2">
          <button ref={cancelRef} onClick={onCancel} className="px-3 py-1 text-sm border border-az-border rounded hover:bg-az-bg text-az-text">
            {t('common.cancel')}
          </button>
          <button onClick={onConfirm} className="px-3 py-1 text-sm bg-az-red rounded hover:bg-red-600 text-white">
            {t('common.confirm')}
          </button>
        </div>
      </div>
    </div>
  )
}
