import { useState, useEffect, useCallback, useRef } from 'react'
import { MessageSquare, Bot, AlertTriangle, HelpCircle, X } from 'lucide-react'

export interface ToastNotification {
  id: string
  type: 'dm.new' | 'human_api.new' | 'human_api.timeout' | 'sla.breach' | 'handoff.expired' | 'generic'
  title: string
  body: string
  at: number // Date.now()
}

const TYPE_CFG = {
  'dm.new':              { Icon: MessageSquare, color: 'bg-[#00a884]',    border: 'border-[#008f72]' },
  'human_api.new':       { Icon: Bot,           color: 'bg-cyan-500',     border: 'border-cyan-600'  },
  'human_api.timeout':   { Icon: Bot,           color: 'bg-slate-500',    border: 'border-slate-600' },
  'sla.breach':          { Icon: AlertTriangle, color: 'bg-red-500',      border: 'border-red-600'   },
  'handoff.expired':     { Icon: AlertTriangle, color: 'bg-amber-500',    border: 'border-amber-600' },
  'generic':             { Icon: HelpCircle,    color: 'bg-[#54656f]',    border: 'border-[#3b4a50]' },
} as const

const AUTO_DISMISS_MS = 5000

interface Props {
  notifications: ToastNotification[]
  onDismiss: (id: string) => void
}

function Toast({ notif, onDismiss }: { notif: ToastNotification; onDismiss: () => void }) {
  const cfg = TYPE_CFG[notif.type] || TYPE_CFG.generic
  const { Icon, color, border } = cfg
  const progressRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const el = progressRef.current
    if (!el) return
    el.style.transition = 'none'
    el.style.width = '100%'
    // force reflow
    void el.offsetWidth
    el.style.transition = `width ${AUTO_DISMISS_MS}ms linear`
    el.style.width = '0%'
  }, [])

  useEffect(() => {
    const t = setTimeout(onDismiss, AUTO_DISMISS_MS)
    return () => clearTimeout(t)
  }, [onDismiss])

  return (
    <div
      className={`relative flex items-start gap-3 w-80 bg-white rounded-xl shadow-xl border ${border} overflow-hidden`}
      style={{ borderLeftWidth: 4 }}
    >
      {/* Barra de progresso */}
      <div
        ref={progressRef}
        className={`absolute bottom-0 left-0 h-0.5 ${color}`}
        style={{ width: '100%' }}
      />

      {/* Ícone */}
      <div className={`flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-lg ${color} text-white ml-3 mt-3`}>
        <Icon size={16} />
      </div>

      {/* Conteúdo */}
      <div className="flex-1 min-w-0 py-3 pr-2">
        <p className="text-[13px] font-semibold text-[#111b21] truncate">{notif.title}</p>
        <p className="text-[12px] text-[#667781] mt-0.5 line-clamp-2">{notif.body}</p>
      </div>

      {/* Fechar */}
      <button
        onClick={onDismiss}
        className="flex-shrink-0 p-1.5 mt-2 mr-2 text-[#8696a0] hover:text-[#111b21] hover:bg-[#f0f2f5] rounded-lg transition"
      >
        <X size={13} />
      </button>
    </div>
  )
}

/** Renderiza a pilha de toasts no canto inferior direito */
export default function NotificationToast({ notifications, onDismiss }: Props) {
  if (notifications.length === 0) return null

  return (
    <div className="fixed bottom-4 right-4 z-[9999] flex flex-col gap-2 items-end">
      {notifications.map(n => (
        <Toast key={n.id} notif={n} onDismiss={() => onDismiss(n.id)} />
      ))}
    </div>
  )
}

/** Hook para gerenciar notificações */
export function useNotifications() {
  const [notifications, setNotifications] = useState<ToastNotification[]>([])

  const push = useCallback((notif: Omit<ToastNotification, 'id' | 'at'>) => {
    const id = `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`
    setNotifications(prev => [...prev.slice(-4), { ...notif, id, at: Date.now() }])
  }, [])

  const dismiss = useCallback((id: string) => {
    setNotifications(prev => prev.filter(n => n.id !== id))
  }, [])

  return { notifications, push, dismiss }
}
