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 { getMissingKeys } from '../../actions'

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

import { AI } from '@/lib/chat/actions'
import { ChatStaff } from "@/components/chat-staff";

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

type PropsHeader = {
  title: React.ReactNode;
  description?: string;
  /**
   * A set of components displayed in the top right
   * null components are filtered out
   */
  actions?: React.ReactNode[];
};

const PageHeader: React.FC<PropsHeader> = ({ title, description, actions }) => {
  const actionRows: React.ReactNode[][] = [];
  if (actions) {
    for (let i = 0; i < actions.length; i += 3) {
      actionRows.push(actions.slice(i, i + 3));
    }
  }

  return (
    <div className="flex flex-col items-start justify-between w-full gap-2 mb-4 md:items-center md:flex-row md:gap-4">
      <div className="space-y-1 ">
        <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
        <p className="text-sm text-gray-500 dark:text-gray-400">{description}</p>
      </div>
      {actionRows.map((row, i) => (
        <ul
          key={i.toString()}
          className="flex flex-wrap items-center justify-end gap-2 md:gap-4 md:flex-nowrap"
        >
          {row.map((action, i) => (
            // biome-ignore lint/suspicious/noArrayIndexKey: I got nothing better right now
            <li key={i}>{action}</li>
          ))}
        </ul>
      ))}
    </div>
  );
};

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

  // 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 missingKeys = await getMissingKeys()
  return (
    <div className="container m-1 mx-auto">
      <PageHeader title="AI客服" description="" />
      <Separator className="my-6" />
      {/* <CreateWorkspace /> */}

      <div className="flex items-start justify-between gap-16">
        <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 ">

          <div className="h-dvh ">
            <iframe
              width="100%"
              height="80%"
              src="/staffai"
              title="Unkey in Five minutes - YouTube"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
              allowFullScreen
            />
          </div>

          {/* <ChatStaff
            // initialMessages={initialMessages}
            id={id}
            // showLanding
            // avatarUrl={avatarUrl}
            className="h-[80%]"
          /> */}
          {/* <AI initialAIState={{ chatId: id, messages: [] }}>
            <ChatAI
              className="bg-[#ececec]"
              id={id} missingKeys={[]}
            // session={session} 
            // missingKeys={missingKeys} 
            />
          </AI> */}

        </main>

      </div>


    </div>
  );
}
