import { Separator } from "@/components/ui/separator";
// import { db, schema } from "@/lib/db";
// import { ingestAuditLogs } from "@/lib/tinybird";
// import { auth } from "@clerk/nextjs";
// import { newId } from "@aigxion/id";
import { ArrowRight } from "lucide-react";
import { headers } from "next/headers";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
// import { CreateApi } from "./create-api";
// import { AsideContent, CreateWorkspace } from "./create-workspace";
// import { Keys } from "./keys";
import { nanoid } from "nanoid";

import { auth } from '@/auth'
import { Session } from '@/lib/types'

import { Chat as ChatAI } from '@/components-ai/chat'

import { AI } from '@/lib/chat/actions'
import { ChatStaff } from "@/components/chat-staff";
import { queryStaff } from "@/lib/http/staff/service";
import { StaffsInfo, StaffsInfoWithoutId } from "@/lib/http/staff";
import { Metadata } from "next";
import { baseTitle, baseURL, keywordsRoot } from "@/lib/metadata";

type Props = {
  params: {
    locale: string
  }
  searchParams: {
    workspaceId?: string;
    apiId?: string;
    serial_no?: string;
  };
};

export async function generateMetadata({ params, searchParams }: Props): Promise<Metadata> {
  // export async function generateMetadata(ctx: any): Promise<Metadata> {
  // read route params
  // const { frontmatter } = await getPost(params.slug);

  // const { t, i18n } = useTranslation()


  const result = await queryStaff(searchParams.serial_no!)

  console.log("---", result.data)

  const staffsInfo = result.data.data as StaffsInfoWithoutId

  if (!result.data) {
    return notFound();
  }

  // const baseUrl = process.env.VERCEL_URL ? "https://jellyai.xyz" : "http://localhost:3000";
  const baseUrl = process.env.VERCEL_URL ? process.env.VERCEL_URL : baseURL;
  const ogUrl = new URL("/og/blog", baseUrl);
  ogUrl.searchParams.set("title", staffsInfo.name ?? staffsInfo.org_name);

  return {
    // title: {
    //   default: 'JellyAI',
    //   template: `${frontmatter.title} | JellyAI`
    // },
    title: `${staffsInfo.name}`,
    description: staffsInfo.description,
    keywords: keywordsRoot(staffsInfo.name || ""),
    openGraph: {
      title: `${staffsInfo.name} | ${baseTitle}`,
      description: staffsInfo.description,
      // url: `https://unkey.dev/blog/${params.slug}`,
      type: "article",
      images: [
        {
          url: ogUrl.toString(),
          width: 1200,
          height: 630,
          alt: staffsInfo.name,
        },
      ],
      // siteName: "unkey.dev",
    },
    twitter: {
      card: "summary_large_image",
      title: `${staffsInfo.name} | ${baseTitle}`,
      description: staffsInfo.description,
      images: [
        {
          url: ogUrl.toString(),
          width: 1200,
          height: 630,
          alt: staffsInfo.name,
        },
      ],
      // site: "@aigxion",
      // creator: "@aigxion",
    },
    icons: {
      shortcut: staffsInfo.avatar_url || "/favicon.png",
    },
  };
}

export default async function (props: Props) {
  // const { userId } = auth();

  console.log("----staffai------", props)

  // if (props.searchParams.apiId) {
  //   const api = await db.query.apis.findFirst({
  //     where: (table, { eq }) => eq(table.id, props.searchParams.apiId!),
  //   });
  //   if (!api) {
  //     return notFound();
  //   }
  //   return (
  //     <div className="container m-16 mx-auto">
  //       <PageHeader
  //         title="Unkey"
  //         description="Create your first key"
  //         actions={[
  //           <Link
  //             key="skip"
  //             href="/app"
  //             className="flex items-center gap-1 text-sm duration-200 text-content-subtle hover:text-foreground"
  //           >
  //             Skip <ArrowRight className="w-4 h-4" />{" "}
  //           </Link>,
  //         ]}
  //       />

  //       <Separator className="my-6" />

  //       <Keys keyAuthId={api.keyAuthId!} apiId={api.id} />
  //     </div>
  //   );
  // }
  // if (props.searchParams.workspaceId) {
  //   const workspace = await db.query.workspaces.findFirst({
  //     where: (table, { and, eq, isNull }) =>
  //       and(eq(table.id, props.searchParams.workspaceId!), isNull(table.deletedAt)),
  //   });
  //   if (!workspace) {
  //     return redirect("/new");
  //   }
  //   return (
  //     <div className="container m-16 mx-auto">
  //       <PageHeader
  //         title="Unkey"
  //         description="Create a new API"
  //         actions={[
  //           <Link
  //             key="skip"
  //             href="/app"
  //             className="flex items-center gap-1 text-sm duration-200 text-content-subtle hover:text-foreground"
  //           >
  //             Skip <ArrowRight className="w-4 h-4" />{" "}
  //           </Link>,
  //         ]}
  //       />
  //       <Separator className="my-6" />
  //       <CreateApi workspace={workspace} />
  //     </div>
  //   );
  // }

  // if (userId) {
  //   const personalWorkspace = await db.query.workspaces.findFirst({
  //     where: (table, { and, eq, isNull }) =>
  //       and(eq(table.tenantId, userId), isNull(table.deletedAt)),
  //   });

  //   // if no personal workspace exists, we create one
  //   if (!personalWorkspace) {
  //     const workspaceId = newId("workspace");
  //     await db.insert(schema.workspaces).values({
  //       id: workspaceId,
  //       tenantId: userId,
  //       name: "Personal",
  //       plan: "free",
  //       stripeCustomerId: null,
  //       stripeSubscriptionId: null,
  //       features: {},
  //       betaFeatures: {},
  //       subscriptions: null,
  //       createdAt: new Date(),
  //     });
  //     await ingestAuditLogs({
  //       workspaceId: workspaceId,
  //       event: "workspace.create",
  //       actor: {
  //         type: "user",
  //         id: userId,
  //       },
  //       description: `Created ${workspaceId}`,
  //       resources: [
  //         {
  //           type: "workspace",
  //           id: workspaceId,
  //         },
  //       ],

  //       context: {
  //         userAgent: headers().get("user-agent") ?? undefined,
  //         location: headers().get("x-forwarded-for") ?? process.env.VERCEL_REGION ?? "unknown",
  //       },
  //     });

  //     return redirect(`/new?workspaceId=${workspaceId}`);
  //   }
  // }

  // const id = nanoid()
  // const session = (await auth()) as Session
  const result = await queryStaff(props.searchParams.serial_no!)

  console.log("---", result.data)

  const staffsInfo = result.data.data as StaffsInfoWithoutId

  return (
    <div className="container  mx-auto">

      {/* <CreateWorkspace /> */}

      <div className="flex items-start justify-between gap-16 ">
        <div className="min-h-screen w-full">

          <ChatStaff
            // initialMessages={initialMessages}
            id={staffsInfo.id.toString()}
            serial_no={staffsInfo.serial_no}
            // showLanding
            avatarUrl={staffsInfo.avatar_url}
            name={staffsInfo.name}
            org_name={staffsInfo.org_name}
            description={staffsInfo.description}
            initialMessages={staffsInfo.greetings ? [{
              id: staffsInfo.id.toString(),
              content: staffsInfo.greetings,
              role: 'assistant',
              createdAt: new Date(),
            }] : []}
          />
        </div>
        {/* <aside className="w-1/4 flex-col items-start justify-center space-y-16 max-md:hidden md:flex ">
          <AsideContent />
        </aside>
        <main className="w-3/4 min-h-screen h-dvh ">
        </main> */}

      </div>


    </div>
  );
}
