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 { ArrowLeft, 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 { CreateWorkspace } from "./create-workspace";
import { Keys } from "./keys";
import CreateForm from "./create-form";

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}`);
  //   }
  // }

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

      <Link
        // href="/manage"
        href="javascript:history.back()"

        className="flex items-center gap-1 mb-[3rem] text-sm duration-200 text-content-subtle hover:text-foreground"
      >
        <ArrowLeft className="w-4 h-4" /> 返回
      </Link>
      <PageHeader title="创建AI客服" description="" />
      <Separator className="my-6" />
      {/* <CreateWorkspace /> */}
      <CreateForm />


    </div>
  );
}
