"use server"
// import { type prisma.cf_api_keys } from '../../../lib/prisma'
import { getSession } from "@auth0/nextjs-auth0"
import { redirect } from "next/navigation"
import { CreateApiKeyDialog } from "@/app/app/apikeys/dialog-create-api-key"
import { Separator } from "@/components/ui/separator"
import { ApiKeyTable } from "@/app/app/apikeys/api-key-table"
import { type cf_api_keys, PrismaClient } from "@prisma/client"
import PostHogClient from "@/app/app/posthog"

const prisma = new PrismaClient()

export default async function APIKeyGenerator(): Promise<JSX.Element> {
  const session = await getSession()
  if (session == null) {
    redirect("/login")
  }
  const userId = session.user.sub
  console.log("USER ID:", session.user)
  const apiKeys: cf_api_keys[] = await prisma.cf_api_keys.findMany({
    where: { user_id: userId },
  })
  // {/* TODO: Query Auth0 for user's organizations */}
  // const organizations = ["Codeflash AI", "Another Organization"]

  const posthog = PostHogClient()
  posthog.capture({
    distinctId: userId,
    properties: { username: session.nickname },
    event: "webapp-loaded-api-keys",
  })

  await posthog.shutdown()

  return (
    <div>
      <h3 className="scroll-m-20 text-2xl font-semibold tracking-tight max-w-full pb-1">
        API Keys
      </h3>
      <Separator />
      {apiKeys.length === 0 ? (
        <>
          <p className="leading-7 mt-6">
            Welcome! Check out the{" "}
            <a
              href="https://docs.codeflash.ai/getting-started/local-installation"
              target="_blank"
              className="underline"
            >
              Getting Started
            </a>{" "}
            docs, or create your first API key below to start using Codeflash.
          </p>
          <p>
            For help with setting up Codeflash on your codebase, please check out the Docs or{" "}
            <a
              href="https://calendly.com/codeflash-saurabh/codeflash-setup"
              target="_blank"
              className="underline"
            >
              book a call
            </a>{" "}
            with the founder.
          </p>
        </>
      ) : (
        <>
          {" "}
          <p className="leading-7 mt-6">
            These API keys are used to authenticate your requests to Codeflash&apos;s AI services.
          </p>
          <ApiKeyTable apiKeys={apiKeys} />{" "}
        </>
      )}

      <CreateApiKeyDialog />
    </div>
  )
}
