import { useCallback, useEffect, useRef, useState } from "react"
import { useNavigate } from "react-router-dom"
import { BellOutlined } from "@ant-design/icons"
import { Badge, Button, Empty, Popover, Spin, Typography } from "antd"
import type { NotificationItem } from "../../api/notifications"
import {
  getAdminUnreadCount,
  listAdminNotifications,
  markAdminNotificationRead,
} from "../api/notifications"

const { Text } = Typography
const POLL_INTERVAL = 5_000

function relativeTime(value: string | null) {
  if (!value) return ""
  const diff = Date.now() - new Date(value).getTime()
  const min = Math.floor(diff / 60000)
  if (min < 1) return "刚刚"
  if (min < 60) return `${min} 分钟前`
  const hour = Math.floor(min / 60)
  if (hour < 24) return `${hour} 小时前`
  return `${Math.floor(hour / 24)} 天前`
}

function actionUrl(item: NotificationItem) {
  return item.action?.url || item.action_url || item.link || ""
}

export default function AdminNotificationBell() {
  const navigate = useNavigate()
  const [total, setTotal] = useState(0)
  const [items, setItems] = useState<NotificationItem[]>([])
  const [loading, setLoading] = useState(false)
  const [open, setOpen] = useState(false)
  const timerRef = useRef<number | null>(null)

  const refreshCount = useCallback(async () => {
    try {
      const data = await getAdminUnreadCount()
      setTotal(data.total)
    } catch {
      // ignore
    }
  }, [])

  const loadItems = useCallback(async () => {
    setLoading(true)
    try {
      const data = await listAdminNotifications({ category: "ticket", limit: 6 })
      setItems(data.items)
    } catch {
      setItems([])
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    void refreshCount()
    timerRef.current = window.setInterval(() => void refreshCount(), POLL_INTERVAL)
    return () => {
      if (timerRef.current) window.clearInterval(timerRef.current)
    }
  }, [refreshCount])

  const handleOpenChange = (next: boolean) => {
    setOpen(next)
    if (next) void loadItems()
  }

  const openItem = async (item: NotificationItem) => {
    setOpen(false)
    if (!item.is_read) {
      setItems((current) => current.map((row) => row.id === item.id ? { ...row, is_read: true } : row))
      try {
        await markAdminNotificationRead(item.id)
        void refreshCount()
      } catch {
        // ignore
      }
    }
    const url = actionUrl(item)
    if (url) navigate(url)
  }

  const panel = (
    <div style={{ width: 340 }}>
      <div style={{ padding: "10px 16px", borderBottom: "1px solid #f0f0f0" }}>
        <Text strong>工单通知</Text>
      </div>
      <div style={{ maxHeight: 360, overflowY: "auto" }}>
        {loading ? (
          <div style={{ padding: 28, textAlign: "center" }}><Spin /></div>
        ) : items.length === 0 ? (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无通知" style={{ padding: 24 }} />
        ) : (
          items.map((item) => (
            <div
              key={item.id}
              onClick={() => void openItem(item)}
              style={{
                padding: "10px 16px",
                borderBottom: "1px solid #f5f5f5",
                cursor: "pointer",
                background: item.is_read ? "#fff" : "#f0f7ff",
              }}
            >
              <Text strong={!item.is_read} style={{ fontSize: 13, display: "block" }} ellipsis>
                {item.title}
              </Text>
              <Text type="secondary" style={{ fontSize: 12, display: "block" }} ellipsis>
                {item.content}
              </Text>
              <Text type="secondary" style={{ fontSize: 11 }}>
                {relativeTime(item.created_at)}
              </Text>
            </div>
          ))
        )}
      </div>
    </div>
  )

  return (
    <Popover
      open={open}
      onOpenChange={handleOpenChange}
      placement="bottomRight"
      trigger="click"
      content={panel}
      styles={{ content: { padding: 0, overflow: "hidden" } }}
    >
      <Badge count={total} size="small" overflowCount={99}>
        <Button type="text" icon={<BellOutlined />} />
      </Badge>
    </Popover>
  )
}
