"use client";
import { EmptyPlaceholder } from "@/components/dashboard/empty-placeholder";
import { PageHeader } from "@/components/dashboard/page-header";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
// import { PostHogIdentify } from "@/providers/PostHogProvider";
// import { useUser } from "@clerk/nextjs";
import { BookOpen, Code, Search, Settings } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { AttributeListItem, CreateApiButton } from "./create-api-button";
import { SheetClose } from "@/components/ui/sheet";
import { StaffState, StaffsInfo, StaffsInfoWithoutId, queryStaffList } from "@/lib/http/staff";
import { useRouter } from "next/navigation";



export type ApiWithKeys = {
  id: string;
  name: string;
  keys: {
    count: number;
  }[];
}[];

export function ApiList({ apis }: { apis: ApiWithKeys }) {


  const router = useRouter();
  // const { user, isLoaded } = useUser();
  useEffect(() => {
    if (apis.length) {
      setLocalData(apis);
    }
  }, [apis]);

  const [localData, setLocalData] = useState(apis);
  const [staffsList, setStaffsList] = useState<StaffsInfoWithoutId[]>([]);


  useEffect(() => {

    // console.log("------------email", infoRef.current, userData.auth_token)

    async function initFunc() {


      const data = await queryStaffList({})

      setStaffsList(data.data.list)
    }

    initFunc()


  }, []);



  function toString(state: StaffState): string {
    switch (state) {
      case StaffState.Inactive:
        return "未激活";
      case StaffState.Active:
        return "正常";
      case StaffState.ApproachingExpiration:
        return "接近过期";
      case StaffState.Expired:
        return "已过期";
      default:
        return "未知状态";
    }
  }

  const renderContent = (state: StaffState, staffId: number) => {
    switch (state) {
      case StaffState.Inactive:
        return <Button
          variant="default"
          className="justify-start w-full "
          onClick={(e) => {
            e.preventDefault()
            // router.push("/manage/plans");

            router.push(`/manage/plans?staffId=${staffId}`);
          }}
        >
          未激活
        </Button>;
      case StaffState.Active:
        return "正常";
      case StaffState.ApproachingExpiration:
        return "接近过期";
      case StaffState.Expired:
        return "已过期";
      default:
        return "未知状态";
    }
  };


  // if (isLoaded && user) {
  //   PostHogIdentify({ user });
  // }
  return (
    <div>
      <PageHeader title="员工" description="管理你的员工" />
      <Separator className="my-6" />
      <section className="my-4 flex flex-col gap-4 md:flex-row md:items-center">
        {/* <div className="border-border focus-within:border-primary/40 flex h-8 flex-grow items-center gap-2 rounded-md border bg-transparent px-3 py-2 text-sm">
          <Search className="h-4 w-4" />
          <input
            className="placeholder:text-content-subtle flex-grow bg-transparent focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 "
            placeholder="Search.."
            onChange={(e) => {
              const filtered = apis.filter((a) =>
                a.name.toLowerCase().includes(e.target.value.toLowerCase()),
              );
              setLocalData(filtered);
            }}
          />
        </div> */}
        {/* <CreateApiButton key="createApi" /> */}

        <Link href="/manage/new">
          <Button variant="default" className="justify-start w-full ">
            <Settings className="w-4 h-4 mr-2" />
            创建AI员工
          </Button>
        </Link>
      </section>
      {apis.length ? (
        <ul className="grid grid-cols-1 gap-x-6 gap-y-8 lg:grid-cols-2 xl:grid-cols-3">
          {staffsList.map((api) => (


            <Link key={api.id} href={`/manage/staffs/${api.id}`}>
              <Card className="hover:border-primary/50 group relative overflow-hidden duration-500 ">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="truncate">{api.name}</CardTitle>
                  </div>
                  {/* http://localhost:3000/staffai/xxxxx/ */}
                  {/* <CardDescription>{`${window.location.origin}/staffai/${api.id}`}</CardDescription> */}
                  <CardDescription>{`${api.id}`}</CardDescription>
                </CardHeader>
                <CardContent>
                  <dl className="divide-y divide-gray-100 text-sm leading-6 ">
                    <div className="flex justify-between gap-x-4 py-3">
                      <dt className="text-gray-500 dark:text-gray-400">AI 员工</dt>
                      <dd className="flex items-start gap-x-2">
                        <div className="font-medium text-gray-900 dark:text-gray-200">
                          {/* {api.keys.at(0)?.count ?? 0} */}
                          {renderContent(api.state as StaffState, api.id)}

                          {/* {toString(api.state as StaffState)} */}
                        </div>
                      </dd>
                    </div>
                  </dl>
                </CardContent>
              </Card>
            </Link>
          ))}
        </ul>
      ) : (
        <EmptyPlaceholder className="my-4 ">
          <EmptyPlaceholder.Icon>
            <Code />
          </EmptyPlaceholder.Icon>
          <EmptyPlaceholder.Title>No APIs found</EmptyPlaceholder.Title>
          <EmptyPlaceholder.Description>
            You haven&apos;t created any APIs yet. Create one to get started.
          </EmptyPlaceholder.Description>
          <div className="flex flex-col items-center justify-center gap-2 md:flex-row">
            <CreateApiButton key="createApi" onCancel={function (): void {
              throw new Error("Function not implemented.");
            }} onSubmit={function (values: AttributeListItem): void {
              throw new Error("Function not implemented.");
            }} createModalVisible={false} />
            <Link href="/docs" target="_blank">
              <Button variant="secondary" className="w-full items-center gap-2 ">
                <BookOpen className="h-4 w-4 md:h-5 md:w-5" />
                Read the docs
              </Button>
            </Link>
          </div>
        </EmptyPlaceholder>
      )}
    </div>
  );
}
