import { useState } from 'react'
import { AlertTriangle, X } from 'lucide-react'
import { useCreditsStatus } from '@/hooks/useUsage'
import { t } from '@/lib/i18n'
import { useNavigate, useLocation } from 'react-router-dom'

export function CreditAlertBanner() {
  const credits = useCreditsStatus()
  const [dismissed, setDismissed] = useState<string | null>(null)
  const navigate = useNavigate()
  const location = useLocation()

  if (location.pathname === '/usage') return null
  if (credits.isLoading || credits.isError || !credits.data) return null

  const cd = credits.data as any
  const num = (v: unknown) => (typeof v === 'number' ? v : 0)

  const boostTotal = num(cd?.boost_credits?.total)
  const boostRemaining = Math.max(0, boostTotal - num(cd?.boost_credits?.used))
  const percent = boostTotal > 0 ? (boostRemaining / boostTotal) * 100 : 100

  // The backend `allowed` flag / site_status is the authoritative service gate. The banner
  // must NOT declare the bot "offline" merely because the purchased bucket is empty while
  // free or subscription credits remain (consumption order is Free ← Subscription ← Purchased).
  const serviceBlocked = cd?.allowed === false || cd?.site_status === 'disabled'

  let level: 'critical' | 'urgent' | 'warning' | null = null
  if (serviceBlocked) {
    level = 'critical'
  } else if (boostTotal > 0) {
    // Low-balance nudges are based on the purchased bucket the user tops up.
    if (percent <= 10) level = 'urgent'
    else if (percent <= 20) level = 'warning'
  }

  if (!level) return null
  if (dismissed === level) return null

  const config = {
    critical: {
      bg: 'bg-red-50',
      border: 'border-red-200',
      text: 'text-red-800',
      icon: 'text-red-500',
      message: t('Your BoostCoins are depleted. The chatbot is offline.'),
      cta: t('Purchase credits'),
    },
    urgent: {
      bg: 'bg-orange-50',
      border: 'border-orange-200',
      text: 'text-orange-800',
      icon: 'text-orange-500',
      message: t('Your BoostCoins are almost depleted') + ` (${Math.round(percent)}% ${t('remaining')}).`,
      cta: t('Top up now'),
    },
    warning: {
      bg: 'bg-yellow-50',
      border: 'border-yellow-200',
      text: 'text-yellow-800',
      icon: 'text-yellow-600',
      message: t('Your BoostCoins are running low') + ` (${Math.round(percent)}% ${t('remaining')}).`,
      cta: t('View usage'),
    },
  }

  const c = config[level]

  return (
    <div className={`${c.bg} border-b ${c.border} ${c.text} px-6 py-3 flex items-center gap-3 text-sm`}>
      <AlertTriangle className={`w-4 h-4 ${c.icon} flex-shrink-0`} />
      <span className="flex-1">{c.message}</span>
      <button
        type="button"
        onClick={() => navigate('/usage')}
        className={`${c.text} font-semibold underline hover:no-underline bg-transparent border-none cursor-pointer text-sm whitespace-nowrap`}
      >
        {c.cta}
      </button>
      {level !== 'critical' && (
        <button
          type="button"
          onClick={() => setDismissed(level)}
          className="p-1 hover:bg-black/5 rounded bg-transparent border-none cursor-pointer"
          title={t('Dismiss')}
        >
          <X className="w-3.5 h-3.5" />
        </button>
      )}
    </div>
  )
}
