import { useEffect, useState } from "react";
import { useLiveChannels, useMovies, useSeries } from "@/hooks/useXtreamData";
import {
  getManagedCounts,
  getManagedProfileId,
  setManagedCounts,
  type ManagedCounts,
} from "@/hooks/useSubscriberProfileSync";
import { useProfiles } from "@/hooks/useProfiles";

/**
 * Live, reactive counts for the admin-managed Xtream profile.
 *
 * Reads from the React Query cache when the managed profile's lists are
 * loaded, otherwise falls back to the last known snapshot stored in
 * localStorage. Any time fresh data arrives (e.g. after the user taps
 * "Reload Playlist"), the counts update automatically and the snapshot
 * is refreshed.
 *
 * Returns `null` if no managed profile exists.
 */
export const useManagedCounts = (): ManagedCounts | null => {
  const { profiles } = useProfiles();
  const managedId = getManagedProfileId();
  const managed = managedId ? profiles.find((p) => p.id === managedId) ?? null : null;

  // Subscribe to the three lists for the managed profile (if it exists).
  // These queries are already cached globally, so this does not trigger
  // extra network calls when the pages have already fetched.
  const liveQ = useLiveChannels(managed);
  const moviesQ = useMovies(managed);
  const seriesQ = useSeries(managed);

  const [snapshot, setSnapshot] = useState<ManagedCounts | null>(getManagedCounts);

  useEffect(() => {
    // Pick up external updates (e.g. from useSubscriberProfileSync or
    // another tab).
    const onChange = () => setSnapshot(getManagedCounts());
    window.addEventListener("nadiplay-managed-counts-changed", onChange);
    window.addEventListener("storage", onChange);
    return () => {
      window.removeEventListener("nadiplay-managed-counts-changed", onChange);
      window.removeEventListener("storage", onChange);
    };
  }, []);

  useEffect(() => {
    if (!managed) return;
    // Only write back when all three queries have data (avoid flashing zeros
    // during a reload).
    const a = liveQ.data?.length;
    const b = moviesQ.data?.length;
    const c = seriesQ.data?.length;
    if (a === undefined || b === undefined || c === undefined) return;
    // Skip no-op writes to avoid extra storage events.
    if (snapshot && snapshot.channels === a && snapshot.movies === b && snapshot.series === c) {
      return;
    }
    setManagedCounts({ channels: a, movies: b, series: c });
    setSnapshot({ channels: a, movies: b, series: c, updatedAt: Date.now() });
  }, [managed, liveQ.data, moviesQ.data, seriesQ.data, snapshot]);

  if (!managedId) return null;
  return snapshot;
};
