"use client"

import { createClient } from "@/utils/supabase/client"
import { Chip, Code, Skeleton } from "@heroui/react"
import useSWR from "swr"

export default function Page() {
  return <CfgxList />
}

function CfgxList() {
  const noticeFetcher = async () => {
    const supabase = createClient()
    const { data /* , error  */ } = await supabase
      .from("CFGX")
      .select(
        "created_at, updated_at, cfgx_version, title, description, version, author, content, alias_list, key_list, value_list",
      )
      .order("created_at", { ascending: false })

    return data as CfgxCardProps[]
  }

  const { data: cfgx /* , error */, isLoading } = useSWR<CfgxCardProps[]>(
    "/api/cfgx",
    noticeFetcher,
  )

  if (isLoading)
    return [1, 2, 3].map((id) => (
      <Skeleton className="mb-3 rounded-lg" key={id}>
        <div className="h-16" />
      </Skeleton>
    ))

  return (
    <ul className="flex flex-col gap-3">
      {cfgx?.map((cfgx) => (
        <CfgxCard key={cfgx.title} {...cfgx} />
      ))}
    </ul>
  )
}

interface CfgxCardProps {
  created_at: string
  updated_at: string
  cfgx_version: string
  title: string
  description: string
  version: string
  author: string
  content: string
  alias_list?: {
    id: string
    info: string
    value: string
  }
  key_list?: {
    id: string
    info: string
    value: string
  }
  value_list?: {
    id: string
    info: string
    value: string
  }
}

function CfgxCard(props: CfgxCardProps) {
  return (
    <li className="flex flex-col gap-2 p-4 rounded-md bg-zinc-50 dark:bg-zinc-900">
      <span className="flex items-center gap-3">
        <h3 className="text-xl font-semibold">{props.title}</h3>
        <Chip size="sm" className="bg-zinc-200 dark:bg-zinc-800">
          {props.version}
        </Chip>
        <Chip size="sm" className="bg-zinc-200 dark:bg-zinc-800">
          {props.author}
        </Chip>
      </span>
      <p className="text-zinc-600 dark:text-zinc-300">{props.description}</p>
      <Code className="p-3 whitespace-pre-line">{props.content}</Code>
      {props.alias_list && (
        <p className="text-zinc-600 dark:text-zinc-300">
          {props.alias_list.id} {props.alias_list.info} {props.alias_list.value}
        </p>
      )}
    </li>
  )
}
