'use client'
import { useState, useRef, useEffect } from 'react'
import { Bell, FileWarning, PenLine, Plus, X } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import { useOperationsStore } from '@/store/operationsStore'
import { cn } from '@/lib/utils'
import Link from 'next/link'

type NotifType = 'doc_pendiente' | 'firma_pendiente' | 'nueva_operacion'

interface Notif {
  id: string
  type: NotifType
  title: string
  subtitle: string
  operationId: string
  unread: boolean
}

const ICONS: Record<NotifType, React.ElementType> = {
  doc_pendiente: FileWarning,
  firma_pendiente: PenLine,
  nueva_operacion: Plus,
}

const COLORS: Record<NotifType, string> = {
  doc_pendiente: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400',
  firma_pendiente: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  nueva_operacion: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
}

function daysSince(dateStr: string) {
  const diff = Date.now() - new Date(dateStr).getTime()
  return Math.floor(diff / (1000 * 60 * 60 * 24))
}

export function NotificationBell() {
  const operations = useOperationsStore(s => s.operations)
  const [open, setOpen] = useState(false)
  const [dismissed, setDismissed] = useState<Set<string>>(new Set())
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [])

  // Generate notifications from operations state
  const allNotifs: Notif[] = operations.flatMap(op => {
    const notifs: Notif[] = []
    const days = daysSince(op.updated_at)

    if (op.status === 'documentacion_pendiente' && days >= 3) {
      notifs.push({
        id: `doc_${op.id}`,
        type: 'doc_pendiente',
        title: 'Documentación pendiente',
        subtitle: `${op.property_address} — sin movimiento hace ${days} días`,
        operationId: op.id,
        unread: true,
      })
    }

    if (op.status === 'listo_para_firma' && days >= 2) {
      notifs.push({
        id: `firma_${op.id}`,
        type: 'firma_pendiente',
        title: 'Firma pendiente',
        subtitle: `${op.property_address} — contrato listo sin firmar`,
        operationId: op.id,
        unread: true,
      })
    }

    if (daysSince(op.created_at) <= 2) {
      notifs.push({
        id: `new_${op.id}`,
        type: 'nueva_operacion',
        title: 'Nueva operación ingresada',
        subtitle: `${op.internal_code} · ${op.property_address}`,
        operationId: op.id,
        unread: true,
      })
    }

    return notifs
  })

  const notifs = allNotifs.filter(n => !dismissed.has(n.id))
  const unreadCount = notifs.filter(n => n.unread).length

  const dismiss = (id: string, e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setDismissed(prev => new Set([...prev, id]))
  }

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(!open)}
        className="relative p-2 rounded-lg hover:bg-accent transition-colors"
      >
        <Bell size={18} className="text-foreground" />
        {unreadCount > 0 && (
          <span className="absolute top-1 right-1 min-w-[18px] h-[18px] bg-red-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center px-0.5">
            {unreadCount > 9 ? '9+' : unreadCount}
          </span>
        )}
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -8, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -8, scale: 0.95 }}
            transition={{ duration: 0.15 }}
            className="absolute right-0 top-full mt-2 z-50 w-80 bg-card border border-border rounded-xl shadow-xl overflow-hidden"
          >
            <div className="px-4 py-3 border-b border-border flex items-center justify-between">
              <p className="text-sm font-semibold">Notificaciones</p>
              {notifs.length > 0 && (
                <button
                  onClick={() => setDismissed(new Set(allNotifs.map(n => n.id)))}
                  className="text-xs text-muted-foreground hover:text-foreground transition-colors"
                >
                  Marcar todas como leídas
                </button>
              )}
            </div>

            <div className="max-h-80 overflow-y-auto">
              {notifs.length === 0 ? (
                <div className="py-10 text-center">
                  <Bell size={28} className="mx-auto mb-2 text-muted-foreground/30" />
                  <p className="text-sm text-muted-foreground">Sin notificaciones pendientes</p>
                </div>
              ) : (
                notifs.map(n => {
                  const Icon = ICONS[n.type]
                  return (
                    <Link
                      key={n.id}
                      href={`/operaciones/${n.operationId}`}
                      onClick={() => setOpen(false)}
                      className="flex items-start gap-3 px-4 py-3 hover:bg-accent/50 transition-colors border-b border-border last:border-0 group"
                    >
                      <div className={cn('p-1.5 rounded-lg flex-shrink-0 mt-0.5', COLORS[n.type])}>
                        <Icon size={13} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-xs font-semibold text-foreground">{n.title}</p>
                        <p className="text-xs text-muted-foreground mt-0.5 leading-snug">{n.subtitle}</p>
                      </div>
                      <button
                        onClick={e => dismiss(n.id, e)}
                        className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-muted transition-all flex-shrink-0"
                      >
                        <X size={12} className="text-muted-foreground" />
                      </button>
                    </Link>
                  )
                })
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}
