import { useQuery } from "@tanstack/react-query";
import { client } from "@/client";
import type { ContributionHeatmapItem } from "@/client/models/contributionHeatmapItem";

export function ContributionHeatmap() {
  const { data: heatmap } = useQuery({
    queryKey: ["me", "heatmap"],
    queryFn: async () => {
      const res = await client.userContributionHeatmap();
      return res.data;
    },
    retry: false,
  });

  const total = heatmap?.total_contributions ?? 0;
  const items = heatmap?.heatmap ?? [];

  return (
    <section className="mt-10">
      <div className="flex items-center justify-between">
        <h2 className="font-heading font-semibold text-sm text-foreground">
          {total} contributions
        </h2>
        {heatmap && (
          <p className="font-mono text-xs text-muted-foreground">
            {heatmap.start_date} — {heatmap.end_date}
          </p>
        )}
      </div>
      <div className="mt-4 flex flex-wrap gap-[3px]">
        {items.length > 0
          ? items.map((item: ContributionHeatmapItem) => {
              const intensity = Math.min(item.count / 5, 1);
              return (
                <span
                  className="size-[10px] rounded-sm"
                  key={item.date}
                  style={{
                    backgroundColor: item.count === 0
                      ? "var(--color-muted)"
                      : `oklch(${0.35 + intensity * 0.35} ${0.05 + intensity * 0.19} 290)`,
                  }}
                />
              );
            })
          : Array.from({ length: 154 }).map((_, i) => (
              <span
                className={`size-[10px] rounded-sm ${i > 128 && i % 4 !== 0 ? "bg-primary/60" : "bg-muted"}`}
                key={i}
              />
            ))}
      </div>
    </section>
  );
}