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 { Badge } from "@/components/ui/badge";
import type { TeamVersion } from "@/types";
import { formatDateTime, truncateMiddle } from "@/lib/utils";

export function TeamVersions({ versions, loading }: { versions: TeamVersion[]; loading: boolean }) {
  const { t } = useTranslation();
  if (loading) return <LoadingSpinner label={t("common.loading")} />;

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

  if (!sorted.length) {
    return <EmptyState icon={FileCode2} title={t("teams.noVersion")} description={t("teams.createVersionDefine")} />;
  }

  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} />
                <Badge className="border-border bg-muted/60 text-muted-foreground">{readableLabel(version.coordination_mode)}</Badge>
              </div>
              <p className="mt-2 text-sm leading-6 text-muted-foreground">{version.objective ?? t("teams.noObjectiveProvided")}</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("teams.members")}</p>
              <p className="mt-1">{version.member_refs_json.length}</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("teams.notPublished")}</p>
            </div>
            <div className="min-w-0">
              <p className="text-muted-foreground">{t("teams.versionId")}</p>
              <p className="mt-1 truncate font-mono text-xs">{truncateMiddle(version.id, 28)}</p>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function readableLabel(value: string) {
  return value.split(/[_-]+/).filter(Boolean).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join(" ");
}
