"use client"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { EmptyState } from "@/components/ui/empty-state"
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 { cn } from "@/lib/utils"
import { Bell, CheckCheck, Loader2, 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: "系统",
}

const typeVariants: Record<Notification["type"], "info" | "neutral" | "default" | "secondary"> = {
  order: "info",
  community: "neutral",
  system: "neutral",
}

function NotificationItem({ notification }: { notification: Notification }) {
  const Icon = typeIcons[notification.type]

  const content = (
    <div
      className={cn(
        "flex items-start gap-4 p-4 transition-colors group relative",
        notification.read ? "hover:bg-muted/10" : "bg-primary/5 hover:bg-primary/10",
      )}
    >
      <div
        className={cn(
          "h-10 w-10 rounded-full border border-border/40 flex items-center justify-center shrink-0",
          notification.read ? "bg-muted/40" : "bg-background",
        )}
      >
        <Icon
          className={cn("h-4 w-4", notification.read ? "text-muted-foreground" : "text-primary")}
        />
      </div>
      <div className="flex-1 min-w-0 space-y-1">
        <div className="flex items-center gap-2">
          <span
            className={cn(
              "text-sm",
              notification.read ? "text-foreground font-medium" : "text-foreground font-bold",
            )}
          >
            {notification.title}
          </span>
          {!notification.read && (
            <span className="h-1.5 w-1.5 rounded-full bg-primary shrink-0 ml-1" />
          )}
        </div>
        <p className="text-sm text-muted-foreground leading-relaxed">{notification.content}</p>
        <p className="text-xs text-muted-foreground/70">
          {new Date(notification.createdAt).toLocaleString("zh-CN")}
        </p>
      </div>
      <Badge
        variant={typeVariants[notification.type] || "neutral"}
        className="text-[10px] px-1.5 py-0 leading-tight shrink-0 mt-1"
      >
        {typeLabels[notification.type]}
      </Badge>
    </div>
  )

  return notification.link ? (
    <Link
      className="block border-b border-border/60 last:border-0 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary"
      href={notification.link}
    >
      {content}
    </Link>
  ) : (
    <div className="border-b border-border/60 last:border-0">{content}</div>
  )
}

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 (
          <EmptyState
            title="加载中"
            description="正在获取您的通知记录..."
            icon={Loader2}
            className="[&>div>svg]:animate-spin my-4 border-dashed"
          />
        )
      }

      if (loadingError) {
        return (
          <EmptyState
            title="加载失败"
            description={loadingError}
            className="my-4 border-destructive/20 bg-destructive/5"
          />
        )
      }

      if (items.length === 0) {
        return (
          <EmptyState
            title={emptyText}
            description="您的所有相关通知将显示在这里。"
            className="my-4 border-dashed"
          />
        )
      }

      return (
        <div className="rounded-xl border border-border/60 bg-card overflow-hidden my-4 shadow-sm">
          {items.map((notification) => (
            <NotificationItem key={notification.id} notification={notification} />
          ))}
        </div>
      )
    },
    [loading, loadingError],
  )

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      <div className="flex items-center justify-between pb-2 border-b border-border/40">
        <div className="flex items-center gap-3">
          <h1 className="text-2xl font-bold tracking-tight">通知中心</h1>
          {unreadCount > 0 && (
            <Badge variant="default" className="rounded-full px-2 py-0 h-5">
              {unreadCount}
            </Badge>
          )}
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={markAllAsRead}
          disabled={markingAll || unreadCount === 0}
          className="border-border/60"
        >
          <CheckCheck className="mr-1.5 h-4 w-4" />
          全部已读
        </Button>
      </div>

      <Tabs defaultValue="all" className="w-full">
        <TabsList className="bg-transparent border-b border-border/40 w-full justify-start rounded-none p-0 h-10 space-x-6">
          <TabsTrigger
            value="all"
            className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-0 h-10"
          >
            全部
          </TabsTrigger>
          <TabsTrigger
            value="order"
            className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-0 h-10"
          >
            订单
          </TabsTrigger>
          <TabsTrigger
            value="community"
            className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-0 h-10"
          >
            社区
          </TabsTrigger>
          <TabsTrigger
            value="system"
            className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-0 h-10"
          >
            系统
          </TabsTrigger>
        </TabsList>

        <TabsContent value="all" className="outline-none">
          {renderTab(notifications, "暂无通知")}
        </TabsContent>

        <TabsContent value="order" className="outline-none">
          {renderTab(orderNotifs, "暂无订单通知")}
        </TabsContent>

        <TabsContent value="community" className="outline-none">
          {renderTab(communityNotifs, "暂无社区通知")}
        </TabsContent>

        <TabsContent value="system" className="outline-none">
          {renderTab(systemNotifs, "暂无系统通知")}
        </TabsContent>
      </Tabs>
    </div>
  )
}
