import { ProjectDto } from "~/browser-client";
import { CheckCircledIcon } from "@radix-ui/react-icons";
import { useFetcher } from "@remix-run/react";
import { FC, useState } from "react";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { PageDocLink } from "~/pages/layouts/PageDocLink";

type ProviderApiKeysProps = {
  provider: "openai" | "cohere";
  title: string;
  subtitle: string;
  link: string;
  initialKey: string;
  route: string;
};

export const ProviderApiKeys: FC<ProviderApiKeysProps> = ({ provider, title, subtitle, link, initialKey, route }) => {
  const fetcher = useFetcher<{ project: ProjectDto }>();
  const [key, setKey] = useState<string>(initialKey);

  const fetcherApiKey = provider === "openai" ? fetcher.data?.project.openaiApiKey : fetcher.data?.project.cohereApiKey;
  const isSaveDisabled = key === initialKey;
  const showSaved = fetcher.state === "idle" && fetcherApiKey && key.startsWith(fetcherApiKey.replaceAll("*", ""));

  const handleSubmit = () => {
    fetcher.submit(
      {
        key,
      },
      {
        method: "POST",
        action: route,
        encType: "application/json",
      },
    );
  };

  return (
    <div className={"w-1/2"}>
      <Label>{title}</Label>
      <p className={"text-muted-foreground mb-2 text-sm"}>
        {subtitle}&nbsp;<PageDocLink to={link}>Get your keys here.</PageDocLink>
      </p>
      <div className={"flex gap-2"}>
        <Input placeholder={"API Key"} value={key} onChange={(e) => setKey(e.target.value)} />
        <Button onClick={handleSubmit} disabled={isSaveDisabled} className={"flex gap-1"}>
          {showSaved && <CheckCircledIcon className={"h-4 w-4"} />}
          {showSaved ? "Saved" : "Save"}
        </Button>
      </div>
    </div>
  );
};
