import {
  FineTuneWithDatasetDto,
  FineTuneWithDatasetDtoProviderEnum,
  FineTuneWithDatasetDtoStatusEnum,
} from "~/browser-client";
import { Link, useParams } from "@remix-run/react";
import dayjs from "dayjs";
import _ from "lodash";
import { ExternalLink } from "lucide-react";
import { FC } from "react";
import { LoadingSpinner } from "~/components/LoadingIcon";
import { Badge } from "~/components/ui/badge";
import { TableCell, TableRow } from "~/components/ui/table";
import { idShortener } from "~/pages/traces/utils";
import { Routes } from "~/routes";

export const FineTuneCell: FC<{ finetune: FineTuneWithDatasetDto }> = ({ finetune }) => {
  const params = useParams();
  const metadata = finetune.metadata as any;

  const { variant } = idShortener(finetune.id);

  const toMap: Record<FineTuneWithDatasetDtoProviderEnum, string | null> = {
    [FineTuneWithDatasetDtoProviderEnum.Openai]: `https://platform.openai.com/finetune/${metadata.id}`,
    [FineTuneWithDatasetDtoProviderEnum.Montelo]: null,
    [FineTuneWithDatasetDtoProviderEnum.Cohere]: `https://dashboard.cohere.com/fine-tuning/custom/${metadata.id}`,
  };

  const nameMap: Record<FineTuneWithDatasetDtoProviderEnum, string> = {
    [FineTuneWithDatasetDtoProviderEnum.Openai]: metadata.fine_tuned_model,
    [FineTuneWithDatasetDtoProviderEnum.Montelo]: metadata.fireworksFineTuneId,
    [FineTuneWithDatasetDtoProviderEnum.Cohere]: metadata.id,
  };

  const to = toMap[finetune.provider];
  const name = nameMap[finetune.provider];

  const showLoader =
    finetune.status === FineTuneWithDatasetDtoStatusEnum.Pending ||
    finetune.status === FineTuneWithDatasetDtoStatusEnum.Running ||
    finetune.status === FineTuneWithDatasetDtoStatusEnum.Deploying;

  return (
    <TableRow key={finetune.id}>
      <TableCell>{name ? <Badge variant={variant}>{name}</Badge> : "—"}</TableCell>
      <TableCell>
        <Link
          to={Routes.app.project.env.datasetsId({
            projectId: params.projectId!,
            envId: params.envId!,
            datasetId: finetune.dataset.id,
          })}
          className={"flex gap-1"}
        >
          <ExternalLink className={"h-4 w-4"} />
          <p>{finetune.dataset.name}</p>
        </Link>
      </TableCell>
      <TableCell>{finetune.model}</TableCell>
      <TableCell className={"flex"}>
        {showLoader ? <LoadingSpinner size={20} /> : null}&nbsp;{_.capitalize(finetune.status)}
      </TableCell>
      <TableCell>{finetune.startedAt ? dayjs(finetune.startedAt).format("h:mma D/M/YY") : "—"}</TableCell>
      <TableCell>{finetune.endedAt ? dayjs(finetune.endedAt).format("h:mma D/M/YY") : "—"}</TableCell>
      <TableCell>
        {to ? (
          <Link to={to} target={"_blank"} rel={"noopener noreferrer"}>
            <ExternalLink className={"h-4 w-4"} />
          </Link>
        ) : null}
      </TableCell>
    </TableRow>
  );
};
