'use client'

import React, { useEffect, useMemo } from 'react'
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerClose,
  DrawerTitle,
} from '@/components/ui/drawer'
import { Button, IconButton } from '@/components/ui/button'
import { InfiniteScrollList } from '@/components/ui/infinite-scroll-list'
import { useUserNoticeListInfinite } from '@/hooks/auth'
import { MessageListOutput } from '@/services/user/types'
import Empty from '@/components/ui/empty'
import { useQueryClient } from '@tanstack/react-query'
import { userKeys } from '@/lib/query-keys'
import { getConversationTime } from '@/lib/utils'
import { useRouter } from 'next/navigation'
import dayjs from 'dayjs'

enum CheckMessageType {
  MEMBER_RENEW_SUCCESS = 102,
  MEMBER_RENEW_FAIL = 103,
  AI_GIFT = 104,
  AI_IMG_UNLOCK = 105,
  HEARTBEAT_LEVEL_DOWN = 106,
}

const RenderCheckButton = ({
  notice,
  onOpenChange,
}: {
  notice: MessageListOutput
  onOpenChange: (open: boolean) => void
}) => {
  const router = useRouter()
  const { extras } = notice || {}

  const { aiId } = JSON.parse(extras || '{}')

  const checkURIMap = {
    [CheckMessageType.MEMBER_RENEW_SUCCESS]: '/vip',
    [CheckMessageType.MEMBER_RENEW_FAIL]: '/vip',
    [CheckMessageType.AI_GIFT]: '/wallet/transactions',
    [CheckMessageType.AI_IMG_UNLOCK]: '/wallet/transactions',
    [CheckMessageType.HEARTBEAT_LEVEL_DOWN]: `/chat/${aiId}`,
  }

  const checkURI = checkURIMap[notice.type as CheckMessageType]

  const handleCheck = () => {
    if (checkURI) {
      router.push(checkURI)
      onOpenChange(false)
    }
  }

  if (!checkURI) {
    return null
  }

  return (
    <Button size="small" variant="tertiary" onClick={handleCheck}>
      Check
    </Button>
  )
}

// 通知项组件
const NoticeListItem: React.FC<{
  notice: MessageListOutput
  onOpenChange: (open: boolean) => void
}> = ({ notice, onOpenChange }) => {
  const renderContent = () => {
    const { extras, content } = notice || {}
    if (notice.type === CheckMessageType.MEMBER_RENEW_SUCCESS) {
      const { expireTime } = JSON.parse(extras || '{}')
      return content?.replace('%s', dayjs(expireTime).format('MMM DD, YYYY, HH:mm A'))
    }

    return content
  }

  return (
    <div className="bg-surface-nest-normal hover:bg-surface-nest-normal-hover rounded-lg p-4">
      <div className="txt-title-s">{notice.title}</div>
      <div className="txt-body-m mt-2">{renderContent()}</div>
      <div className="mt-2 flex items-center justify-between">
        <div className="txt-numMonotype-xs text-txt-secondary-normal">
          {notice.createTime && getConversationTime(notice.createTime as unknown as number)}
        </div>
        {/* <Button size="small" variant="tertiary">Check</Button> */}
        <RenderCheckButton notice={notice} onOpenChange={onOpenChange} />
      </div>
    </div>
  )
}

// 加载骨架屏组件
const NoticeSkeleton = () => (
  <div className="bg-surface-nest-normal animate-pulse rounded-lg p-4">
    <div className="bg-surface-element-normal mb-2 h-4 rounded" />
    <div className="bg-surface-element-normal mb-1 h-3 rounded" />
    <div className="bg-surface-element-normal mb-2 h-3 w-3/4 rounded" />
    <div className="flex items-center justify-between">
      <div className="bg-surface-element-normal h-3 w-16 rounded" />
      <div className="bg-surface-element-normal h-6 w-12 rounded" />
    </div>
  </div>
)

interface NoticeDrawerProps {
  isOpen: boolean
  onOpenChange: (open: boolean) => void
}

const NoticeDrawer: React.FC<NoticeDrawerProps> = ({ isOpen, onOpenChange }) => {
  // 使用无限滚动钩子获取通知列表，只在抽屉打开时启用
  const { data, fetchNextPage, hasNextPage, isLoading, isFetchingNextPage, error, refetch } =
    useUserNoticeListInfinite(20, isOpen)

  const queryClient = useQueryClient()

  // 合并所有页面的数据
  const allNotices = useMemo(() => {
    return data?.pages.flatMap((page) => page.datas || []) || []
  }, [data])

  useEffect(() => {
    if (isOpen && allNotices.length > 0) {
      queryClient.invalidateQueries({
        queryKey: userKeys.noticeStat(),
      })
    }

    if (isOpen) {
      refetch()
    }
  }, [isOpen, allNotices])

  return (
    <Drawer open={isOpen} onOpenChange={onOpenChange} direction="right">
      <DrawerContent className="border-outline-normal h-full w-96 max-w-[90vw] border-r">
        <DrawerTitle></DrawerTitle>
        <DrawerHeader className="flex h-20 items-center justify-center">
          <div className="txt-title-l">Notice</div>
          <DrawerClose asChild>
            <IconButton
              size="small"
              variant="ghost"
              iconfont="icon-close"
              className="absolute top-6 right-6"
            />
          </DrawerClose>
        </DrawerHeader>

        {/* 通知列表 */}
        <div className="flex-1 overflow-y-auto px-6 pb-10">
          <InfiniteScrollList<MessageListOutput>
            items={allNotices}
            renderItem={(notice) => <NoticeListItem notice={notice} onOpenChange={onOpenChange} />}
            getItemKey={(notice) => notice.id?.toString() || 'unknown'}
            hasNextPage={!!hasNextPage}
            isLoading={isLoading || isFetchingNextPage}
            fetchNextPage={fetchNextPage}
            columns={1}
            gap={4}
            LoadingSkeleton={NoticeSkeleton}
            EmptyComponent={() => (
              <div className="flex flex-col items-center justify-center py-16 text-center">
                <Empty title="Nothing here… :3" />
              </div>
            )}
            ErrorComponent={() => (
              <div className="flex flex-col items-center justify-center py-16 text-center">
                <Empty title="Nothing here… :3" />
              </div>
            )}
            hasError={!!error}
            onRetry={refetch}
            threshold={200}
            enabled={isOpen}
          />
        </div>
      </DrawerContent>
    </Drawer>
  )
}

export default NoticeDrawer
