"use client"
import {
  Card,
  CardBody,
  CardHeader,
  CardIcon,
  CardTool,
} from "@/components/window/Card"
import { useAppStore } from "@/store/app"
import { createClient } from "@/utils/supabase/client"
import { Skeleton } from "@heroui/react"
import { Refresh, VolumeNotice } from "@icon-park/react"
import useSWR, { useSWRConfig } from "swr"
import { ToolButton } from "../window/ToolButton"

const Notice = () => {
  const { mutate } = useSWRConfig()

  return (
    <Card>
      <CardHeader>
        <CardIcon>
          <VolumeNotice /> 公告
        </CardIcon>
        <CardTool>
          <ToolButton onClick={() => mutate("/api/notice")}>
            <Refresh />
            刷新
          </ToolButton>
        </CardTool>
      </CardHeader>
      <CardBody>
        <NoticeBody />
      </CardBody>
    </Card>
  )
}

const NoticeBody = () => {
  const app = useAppStore()

  const noticeFetcher = async () => {
    const supabase = createClient()
    const { data /* , error */ } = await supabase
      .from("Notice")
      .select("created_at, content, url")
      .order("created_at", { ascending: false })
      .single()

    return data
  }

  const { data: notice /* , error */, isLoading } = useSWR(
    "/api/notice",
    noticeFetcher,
  )

  // if (error) return <>错误：{error}</>
  if (isLoading)
    return (
      <Skeleton className="rounded-lg">
        <div className="h-6" />
      </Skeleton>
    )

  return (
    <>
      {notice?.content ||
        app.state.notice ||
        "不会真的有人要更新CSGO工具箱吧，不会吧不会吧 xswl"}
    </>
  )
}

export default Notice
