import { ApiKeyWithEnvDto, ProjectDto } from "@montelo/browser-client";
import { CheckCircledIcon } from "@radix-ui/react-icons";
import { useFetcher, useMatches, useParams } from "@remix-run/react";
import { FC, useState } from "react";
import { ApiKeysTable } from "~/components/dialogs/ApiKeys/ApiKeysTable";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { PageLayout } from "~/pages/layouts/PageLayout";
import { LayoutBreadcrumb } from "~/pages/layouts/types";
import { Routes } from "~/routes";
import { AppLayoutLoader } from "~/types/AppLayoutLoader.types";

export const ApiKeysPage: FC<{ sortedEnvironments: ApiKeyWithEnvDto[] }> = ({ sortedEnvironments }) => {
  const params = useParams();
  const matches = useMatches();
  const fetcher = useFetcher<{ project: ProjectDto }>();

  const initialKey = (
    matches.find((match) => match.id === "routes/app+/project+/$projectId+/env+/$envId+/_layout")!
      .data as AppLayoutLoader
  ).project.openaiApiKey;

  const [openAIKey, setOpenAIKey] = useState<string>(initialKey);

  const breadcrumbs: LayoutBreadcrumb[] = [
    {
      label: "API Keys",
    },
  ];

  const handleSetOpenAIKey = () => {
    fetcher.submit(
      {
        key: openAIKey,
      },
      {
        method: "POST",
        action: Routes.actions.project.setOpenAIKey(params.projectId!),
        encType: "application/json",
      },
    );
  };

  const isSaveDisabled = openAIKey === initialKey;

  const fetcherApiKey = fetcher.data?.project.openaiApiKey;
  const showSaved =
    fetcher.state === "idle" && fetcherApiKey && openAIKey.startsWith(fetcherApiKey.replaceAll("*", ""));

  return (
    <PageLayout breadcrumbs={breadcrumbs}>
      <div className={"flex flex-col gap-8"}>
        <div>
          <Label>Montelo</Label>
          <ApiKeysTable sortedEnvironments={sortedEnvironments} projectId={params.projectId!} />
        </div>
        <div>
          <Label>OpenAI</Label>
          <p className={"text-muted-foreground text-sm"}>Your OpenAI key will only be used for Fine-Tuning.</p>
          <div className={"flex gap-2"}>
            <Input
              className={"w-1/3"}
              placeholder={"sk-..."}
              value={openAIKey}
              onChange={(e) => setOpenAIKey(e.target.value)}
            />
            <Button onClick={handleSetOpenAIKey} disabled={isSaveDisabled} className={"flex gap-1"}>
              {showSaved && <CheckCircledIcon className={"h-4 w-4"} />}
              {showSaved ? "Saved" : "Save"}
            </Button>
          </div>
        </div>
      </div>
    </PageLayout>
  );
};
