"use client"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { requestWithAuth } from "@/lib/api/client"
import { listNotifications, markAllNotificationsAsRead } from "@/lib/api/notifications"
import { toApiError } from "@/lib/errors"
import { notifyInfo } from "@/lib/toast"
import type { Notification } from "@/lib/types"
import { Bell, CheckCheck, MessageSquare, ShoppingBag } from "lucide-react"
import Link from "next/link"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"

const typeIcons: Record<Notification["type"], typeof Bell> = {
  order: ShoppingBag,
  community: MessageSquare,
  system: Bell,
}

const typeLabels: Record<Notification["type"], string> = {
  order: "订单",
  community: "社区",
  system: "系统",
}

function NotificationItem({ notification }: { notification: Notification }) {
  const Icon = typeIcons[notification.type]
  const content = (
    <Card className="p-0 hover:bg-muted/50 transition-colors">
      <CardContent className="flex items-start gap-3 p-4">
        <div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center shrink-0 mt-0.5">
          <Icon className="h-4 w-4" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium">{notification.title}</span>
            {!notification.read && <span className="h-2 w-2 rounded-full bg-primary shrink-0" />}
          </div>
          <p className="text-sm text-muted-foreground mt-0.5">{notification.content}</p>
          <p className="text-xs text-muted-foreground mt-1">
            {new Date(notification.createdAt).toLocaleString("zh-CN")}
          </p>
        </div>
        <Badge variant="outline" className="text-[10px] shrink-0">
          {typeLabels[notification.type]}
        </Badge>
      </CardContent>
    </Card>
  )
  return notification.link ? (
    <Link className="block" href={notification.link}>
      {content}
    </Link>
  ) : (
    content
  )
}

export default function NotificationsPage() {
  const mountedRef = useRef(true)
  const markAllPendingRef = useRef(false)

  const [notifications, setNotifications] = useState<Notification[]>([])
  const [loading, setLoading] = useState(true)
  const [loadingError, setLoadingError] = useState<string | null>(null)
  const [markingAll, setMarkingAll] = useState(false)

  const loadNotifications = useCallback(async function loadNotifications() {
    setLoading(true)
    setLoadingError(null)

    try {
      const res = await requestWithAuth(() => listNotifications({ offset: 0, limit: 50 }), {
        onUnauthorized: () => loadNotifications(),
      })

      if (!mountedRef.current) return

      if (res === null) {
        setLoading(false)
        return
      }

      setNotifications(res)
      setLoading(false)
    } catch (err: unknown) {
      if (!mountedRef.current) return
      setLoading(false)
      setLoadingError(toApiError(err).msg)
    }
  }, [])

  useEffect(() => {
    mountedRef.current = true
    void loadNotifications()
    return () => {
      mountedRef.current = false
    }
  }, [loadNotifications])

  const markAllAsRead = useCallback(async function markAllAsRead() {
    if (markAllPendingRef.current) return

    markAllPendingRef.current = true
    setMarkingAll(true)

    try {
      const res = await requestWithAuth(() => markAllNotificationsAsRead(), {
        onUnauthorized: () => markAllAsRead(),
      })

      if (!mountedRef.current) return

      if (res === null) {
        return
      }

      setNotifications((prev) => prev.map((n) => (n.read ? n : { ...n, read: true })))
    } catch (err: unknown) {
      if (!mountedRef.current) return
      notifyInfo(toApiError(err).msg)
    } finally {
      markAllPendingRef.current = false
      if (mountedRef.current) setMarkingAll(false)
    }
  }, [])

  const unreadCount = useMemo(
    () => notifications.filter((notification) => !notification.read).length,
    [notifications],
  )
  const orderNotifs = useMemo(
    () => notifications.filter((notification) => notification.type === "order"),
    [notifications],
  )
  const communityNotifs = useMemo(
    () => notifications.filter((notification) => notification.type === "community"),
    [notifications],
  )
  const systemNotifs = useMemo(
    () => notifications.filter((notification) => notification.type === "system"),
    [notifications],
  )

  const renderTab = useCallback(
    (items: Notification[], emptyText: string) => {
      if (loading) {
        return (
          <Card>
            <CardContent className="py-8 text-center text-sm text-muted-foreground">
              加载中...
            </CardContent>
          </Card>
        )
      }

      if (loadingError) {
        return (
          <Card>
            <CardContent className="py-8 text-center text-sm text-muted-foreground">
              {loadingError}
            </CardContent>
          </Card>
        )
      }

      if (items.length === 0) {
        return (
          <Card>
            <CardContent className="py-8 text-center text-sm text-muted-foreground">
              {emptyText}
            </CardContent>
          </Card>
        )
      }

      return items.map((notification) => (
        <NotificationItem key={notification.id} notification={notification} />
      ))
    },
    [loading, loadingError],
  )

  return (
    <div className="container mx-auto max-w-2xl px-4 py-8 space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <h1 className="text-2xl font-bold">通知中心</h1>
          {unreadCount > 0 && <Badge>{unreadCount} 条未读</Badge>}
        </div>
        <Button variant="outline" size="sm" onClick={markAllAsRead} disabled={markingAll}>
          <CheckCheck className="mr-1 h-4 w-4" />
          全部已读
        </Button>
      </div>

      <Tabs defaultValue="all">
        <TabsList>
          <TabsTrigger value="all">全部</TabsTrigger>
          <TabsTrigger value="order">订单</TabsTrigger>
          <TabsTrigger value="community">社区</TabsTrigger>
          <TabsTrigger value="system">系统</TabsTrigger>
        </TabsList>

        <TabsContent value="all" className="flex flex-col gap-3 mt-4">
          {renderTab(notifications, "暂无通知")}
        </TabsContent>

        <TabsContent value="order" className="flex flex-col gap-3 mt-4">
          {renderTab(orderNotifs, "暂无订单通知")}
        </TabsContent>

        <TabsContent value="community" className="flex flex-col gap-3 mt-4">
          {renderTab(communityNotifs, "暂无社区通知")}
        </TabsContent>

        <TabsContent value="system" className="flex flex-col gap-3 mt-4">
          {renderTab(systemNotifs, "暂无系统通知")}
        </TabsContent>
      </Tabs>
    </div>
  )
}
