import remarkGfm from 'remark-gfm'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
import { remark } from 'remark'
import matter from 'gray-matter'
import dayjs from 'dayjs'
import Image from 'next/image'
import { notFound } from 'next/navigation'

async function getData(id: string) {
  let numID = id
  if (id.startsWith('cms_')) {
    numID = id.slice(4)
  }
  const res = await fetch(`${process.env.CMS_ENDPOINT}/knowledges/${numID}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.CMS_API_TOKEN}`,
    },
    next: { revalidate: 60 },
  })
  if (!res.ok) {
    return undefined
  }

  return res.json()
}

export async function generateMetadata({ params }: { params: { id: string } }) {
  const res = await getData(params.id)

  return {
    title: res?.data?.attributes?.question
      ? `${res?.data?.attributes?.question} - PinternalKB`
      : 'PinternalKB',
  }
}

export default async function Page({ params }: { params: { id: string } }) {
  console.time(`fetch cms id: ${params.id}`)
  const res = await getData(params.id)
  console.timeEnd(`fetch cms id: ${params.id}`)

  if (!res || !res?.data) {
    notFound()
  }

  const {
    question = 'Untitled',
    answer = 'To Be Filled...',
    createdAt = '',
    updatedAt = '',
  } = res?.data?.attributes || {}

  const matterResult = matter(answer)
  const processedContent = await remark()
    .use(remarkGfm)
    .use(remarkRehype)
    .use(remarkRehype, { footnoteLabelProperties: { className: ['sr-only'] } })
    .use(rehypeStringify)
    .process(matterResult.content.replace(/^Title[:：][^\n]*\n+/g, ''))
  const contentHtml = processedContent.toString()

  return (
    <div className="max-w-[960px] w-full">
      <div className="flex items-center w-full px-2 pb-4">
        <div className="mr-2">
          <Image src="/logo.svg" alt="PingCAP Logo" width={16} height={16} priority />
        </div>
        <div className="font-bold text-transparent text-md main-gradient bg-clip-text">
          Pinternal KB
        </div>
      </div>
      <div className="w-full shadow-2xl shadow-slate-300/50 border-2 border-white bg-[rgba(255,255,255,0.9)] px-6 py-4  rounded-b-none rounded-t-xl sm:rounded-b-xl sm:px-8 sm:py-6 md:px-10 md:py-8 lg:px-12 lg:py-10 break-all text-justify">
        <h1 className="text-4xl font-bold text-gray-900">{question}</h1>
        <div className="mt-4 mb-2 h-[2px] bg-slate-100"></div>
        <div className="flex items-center justify-between w-full text-xs text-gray-400">
          <div className="flex flex-col md:flex-row md:items-center">
            <div className="md:mr-4">
              <span className="mr-1">Created At:</span>
              <span>{dayjs(createdAt).format('YYYY-MM-DD HH:mm')}</span>
            </div>
            <div>
              <span className="mr-1">Updated At:</span>
              <span>{dayjs(updatedAt).format('YYYY-MM-DD HH:mm')}</span>
            </div>
          </div>
          <div>
            {/* <span>Vector ID:</span>
          <span>{vector_id}</span> */}
          </div>
        </div>
        <div className="prose max-w-none">
          <div dangerouslySetInnerHTML={{ __html: contentHtml }} />
        </div>
      </div>
    </div>
  )
}
