import { useCallback, useEffect, useState } from 'react'
import { Bell, Check } from 'lucide-react'
import { api, LOG_CATEGORY, LOG_STATUS, type AppLog } from '@/api'
import { LOG_EVENTS } from '@/constants'
import { useEventBus } from '@/hooks/useEventBus'
import { formatDateTime } from '@/lib/format'
import { cn } from '@/lib/utils'

export function SystemNotice() {
  const [open, setOpen] = useState(false)
  const [notices, setNotices] = useState<AppLog[]>([])
  const [loading, setLoading] = useState(false)

  const fetchNotices = useCallback(async () => {
    try {
      const res = await api.appLogs.list({
        category: LOG_CATEGORY.SYSTEM_NOTICE,
        status: LOG_STATUS.UNREAD,
        page: 1,
        page_size: 50,
      })
      setNotices(Array.isArray(res?.data) ? res.data : [])
    } catch {
      // ignore
    }
  }, [])

  useEffect(() => {
    fetchNotices()
    const t = window.setInterval(fetchNotices, 10 * 60 * 1000)
    return () => clearInterval(t)
  }, [fetchNotices])

  useEventBus(LOG_EVENTS.ADDED, (log) => {
    if (log?.category === LOG_CATEGORY.SYSTEM_NOTICE) fetchNotices()
  })

  async function markAsRead(id: string) {
    try {
      await api.appLogs.markAsRead({ id })
      setNotices((list) => list.filter((n) => n.id !== id))
    } catch {
      // ignore
    }
  }

  async function markAllAsRead() {
    if (!notices.length) return
    setLoading(true)
    try {
      await api.appLogs.markAsRead({ category: LOG_CATEGORY.SYSTEM_NOTICE })
      setNotices([])
      setOpen(false)
    } catch {
      // ignore
    } finally {
      setLoading(false)
    }
  }

  const unread = notices.length

  return (
    <div className="relative">
      <button
        type="button"
        className="relative inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--border)] bg-[var(--bg-primary)] text-[var(--text-secondary)] transition-colors hover:border-[var(--border-hover)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-primary)]"
        title="系统通知"
        onClick={() => setOpen((v) => !v)}
      >
        <Bell size={15} strokeWidth={1.5} />
        {unread > 0 ? (
          <span className="absolute right-1.5 top-1.5 h-1.5 w-1.5 animate-pulse rounded-full bg-red-500" />
        ) : null}
      </button>

      {open ? (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
          <div className="absolute right-0 top-10 z-50 w-80 overflow-hidden rounded-md border border-[var(--border)] bg-[var(--bg-secondary)] shadow-[var(--shadow-md)]">
            <div className="flex items-center justify-between border-b border-[var(--border)] px-3 py-2">
              <span className="text-sm font-medium">
                系统通知
                {unread ? <span className="ml-1 text-xs text-[var(--text-muted)]">({unread})</span> : null}
              </span>
              <button
                type="button"
                className="inline-flex items-center gap-1 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] disabled:opacity-40"
                disabled={loading || unread === 0}
                onClick={markAllAsRead}
              >
                <Check size={12} />
                全标已读
              </button>
            </div>
            <div className="max-h-[300px] overflow-y-auto">
              {notices.length === 0 ? (
                <div className="flex flex-col items-center py-10 text-sm text-[var(--text-muted)]">
                  <Bell size={28} className="mb-2 opacity-20" />
                  暂无新通知
                </div>
              ) : (
                notices.map((n) => (
                  <button
                    key={n.id}
                    type="button"
                    className="block w-full border-b border-[var(--border)] px-3 py-3 text-left last:border-0 hover:bg-[var(--bg-hover)]"
                    onClick={() => markAsRead(n.id)}
                  >
                    <div className="mb-1 flex items-center gap-2">
                      <span
                        className={cn(
                          'rounded px-1.5 py-0.5 text-[10px]',
                          n.level === 'error'
                            ? 'bg-red-500/15 text-red-500'
                            : n.level === 'warning'
                              ? 'bg-amber-500/15 text-amber-500'
                              : 'bg-[var(--bg-tertiary)] text-[var(--text-muted)]',
                        )}
                      >
                        {n.level === 'error' ? '错误' : n.level === 'warning' ? '警告' : '提示'}
                      </span>
                      <span className="truncate text-sm font-medium">{n.title}</span>
                    </div>
                    <p className="line-clamp-2 text-xs text-[var(--text-muted)]">{n.content}</p>
                    <p className="mt-1 text-[10px] text-[var(--text-muted)]">{formatDateTime(n.created_at)}</p>
                  </button>
                ))
              )}
            </div>
          </div>
        </>
      ) : null}
    </div>
  )
}
