// src/components/content/overview/content-overview-container.tsx
"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { Skeleton } from "@/components/ui/skeleton";
import { getContentOverviewAction } from "@/lib/content/actions";
import type { ContentOverview } from "@/lib/content/overview";
import { useActiveSite } from "@/lib/keywords/site-context";
import { ContentByAssignee } from "./content-by-assignee";
import { ContentOverviewKpis } from "./content-overview-kpis";
import { ContentStatusDistribution } from "./content-status-distribution";
import { ContentUpcoming } from "./content-upcoming";

export function ContentOverviewContainer({
  initialOverview,
  initialSiteId,
}: {
  initialOverview: ContentOverview | null;
  initialSiteId: string;
}) {
  const { activeSiteId } = useActiveSite();
  // The server already provided the overview for this site. Track the loaded
  // site so we never refetch on mount — a read server action on mount triggers
  // an implicit route revalidation that races and deadlocks the next client
  // navigation.
  const loadedSite = useRef(initialSiteId);
  const [ov, setOv] = useState<ContentOverview | null>(initialOverview);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setOv(await getContentOverviewAction(activeSiteId));
    setLoading(false);
  }, [activeSiteId]);

  useEffect(() => {
    // Only refetch when the site actually changes — never on mount.
    if (activeSiteId === loadedSite.current) return;
    loadedSite.current = activeSiteId;
    void load().catch(() => setLoading(false));
  }, [activeSiteId, load]);

  if (loading || !ov) {
    return (
      <div className="space-y-3 p-4">
        <Skeleton className="h-20 w-full" />
        <Skeleton className="h-64 w-full" />
      </div>
    );
  }

  if (ov.total === 0) {
    return (
      <div className="flex h-64 flex-col items-center justify-center gap-2 text-muted-foreground">
        <p>Aucun article pour ce site.</p>
        <p className="text-sm">
          Créez des articles depuis le planning ci-dessous pour commencer.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4 p-4">
      <ContentOverviewKpis ov={ov} />
      <div className="grid gap-4 lg:grid-cols-2">
        <ContentStatusDistribution ov={ov} />
        <ContentByAssignee ov={ov} />
      </div>
      <ContentUpcoming ov={ov} />
    </div>
  );
}
