import { useQuery } from "@tanstack/react-query";
import { prCommitsList } from "@/client";
import { GitCommit, Loader2 } from "lucide-react";

interface PRCommitListProps {
  namespace: string;
  repoName: string;
  prNumber: number;
}

const getRelativeTime = (dateString: string | null | undefined) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
  if (diffInSeconds < 60) return "just now";
  if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}m ago`;
  if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}h ago`;
  if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)}d ago`;
  return `${Math.floor(diffInSeconds / 2592000)}mo ago`;
};

export function PRCommitList({ namespace, repoName, prNumber }: PRCommitListProps) {
  const { data, isLoading } = useQuery({
    queryKey: ["pr-commits", namespace, repoName, prNumber],
    queryFn: async () => {
      const resp = await prCommitsList({
        path: { namespace, repo: repoName, pr_number: prNumber },
      });
      return resp.data?.data?.commits ?? [];
    },
    enabled: !!namespace && !!repoName && !!prNumber,
    staleTime: 60 * 1000,
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-32">
        <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
        <span className="ml-2 text-sm text-muted-foreground">Loading commits...</span>
      </div>
    );
  }

  if (!data || data.length === 0) {
    return (
      <div className="text-center text-muted-foreground text-sm py-8">
        No commits in this pull request.
      </div>
    );
  }

  return (
    <div className="divide-y divide-border/50">
      {data.map((commit) => (
        <div
          key={commit.oid}
          className="flex items-start gap-3 p-3 hover:bg-muted/30 transition-colors"
        >
          <GitCommit className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-0.5" />
          <div className="flex-1 min-w-0">
            <p className="text-sm truncate leading-tight">{commit.summary}</p>
            <div className="flex flex-wrap items-center gap-x-3 gap-y-0.5 mt-1">
              <span className="font-mono text-xs text-muted-foreground">
                {commit.short_oid}
              </span>
              <span className="text-xs text-muted-foreground">
                {commit.author_name}
              </span>
              <span className="text-xs text-muted-foreground">
                {getRelativeTime(commit.authored_at)}
              </span>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
