import { useQuery } from "@tanstack/react-query";
import { getMetrics, getStatus, deleteRepo } from "../api/client";
import ChartPanel from "./ChartPanel";
import StatusBadge from "./StatusBadge";
import { useAppStore } from "../store/useAppStore";
import { useAutoRefresh } from "../hooks/useAutoRefresh";

export default function RepoCard({ repo }) {
  const { selectedRange, autoRefresh } = useAppStore();

  const metricsQuery = useQuery({
    queryKey: ["metrics", repo.id, selectedRange],
    queryFn: () => getMetrics(repo.id, selectedRange),
  });

  const statusQuery = useQuery({
    queryKey: ["status", repo.id],
    queryFn: () => getStatus(repo.id),
  });

  useAutoRefresh(metricsQuery.refetch, autoRefresh);
  useAutoRefresh(statusQuery.refetch, autoRefresh);

  return (
    <div className="bg-zinc-900 p-4 rounded-xl shadow-lg">
      <div className="flex justify-between">
        <h2>{repo.namespace}/{repo.repo}</h2>
        <button onClick={() => deleteRepo(repo.id)}>❌</button>
      </div>
	  
	  if (metricsQuery.isLoading) return <p>Loading...</p>;
	  if (metricsQuery.isError) return <p>Error loading metrics</p>;

      {statusQuery.data && (
        <StatusBadge
          state={statusQuery.data.state}
          stage={statusQuery.data.stage}
        />
      )}

      {metricsQuery.data ? (
        <>
          <ChartPanel data={metricsQuery.data} metric="cpu" />
          <ChartPanel data={metricsQuery.data} metric="memory" />
        </>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}