import { useTranslation } from "react-i18next";
import { FileCode2 } from "lucide-react";
import { EmptyState } from "@/components/shared/EmptyState";
import { LoadingSpinner } from "@/components/shared/LoadingSpinner";
import { StatusBadge } from "@/components/shared/StatusBadge";
import { formatDateTime } from "@/lib/utils";
import type { AgentVersion } from "@/types";

export function AgentVersions({ versions, loading }: { versions: AgentVersion[]; loading: boolean }) {
  const { t } = useTranslation();
  if (loading) return <LoadingSpinner label={t("common.loading")} />;
  if (!versions.length) return <EmptyState icon={FileCode2} title={t("agents.noVersions")} description={t("agents.createVersionDefine")} />;

  const sorted = [...versions].sort((a, b) => b.version_no - a.version_no);

  return (
    <div className="space-y-3">
      {sorted.map((version) => (
        <div key={version.id} className="rounded-md border border-border bg-muted/30 p-4">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div>
              <div className="flex flex-wrap items-center gap-2">
                <p className="font-medium">v{version.version_no}</p>
                <StatusBadge status={version.status} />
              </div>
              <p className="mt-1 text-sm text-muted-foreground">{version.goal ?? t("agents.noDescription")}</p>
            </div>
            <p className="text-xs text-muted-foreground">{formatDateTime(version.created_time)}</p>
          </div>
          <div className="mt-4 grid gap-3 text-sm md:grid-cols-3">
            <div className="min-w-0">
              <p className="text-muted-foreground">{t("agents.role")}</p>
              <p className="mt-1">{version.role}</p>
            </div>
            <div className="min-w-0">
              <p className="text-muted-foreground">{t("agents.model")}</p>
              <p className="mt-1 truncate font-mono text-xs">{stringifyConfigValue(version.model_config_json.model) ?? t("agents.noDescription")}</p>
            </div>
            <div className="min-w-0">
              <p className="text-muted-foreground">{t("agents.published")}</p>
              <p className="mt-1">{version.published_time ? formatDateTime(version.published_time) : t("agents.notPublished")}</p>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function stringifyConfigValue(value: unknown) {
  if (typeof value === "string") return value;
  if (typeof value === "number" || typeof value === "boolean") return String(value);
  return undefined;
}
