import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Database, Loader2, Pause, Play } from "lucide-react";
import { api } from "../lib/api";
import { formatViews } from "../lib/format";

export default function SyncStatus() {
  const qc = useQueryClient();
  const { data } = useQuery({
    queryKey: ["sync-status"],
    queryFn: api.status,
    refetchInterval: 30_000,
    staleTime: 25_000,
  });

  const toggle = useMutation({
    mutationFn: () => (data?.paused ? api.resumeSync() : api.pauseSync()),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["sync-status"] }),
  });

  if (!data) return null;

  return (
    <div className="hidden lg:flex items-center gap-2 text-xs text-muted">
      <Database className="w-3.5 h-3.5" />
      <span>{formatViews(data.videos_total)} videos</span>
      <span className="opacity-40">·</span>
      {data.paused ? (
        <span className="text-accent font-medium">paused</span>
      ) : data.channels_backfilling > 0 ? (
        <span className="flex items-center gap-1">
          <Loader2 className="w-3.5 h-3.5 animate-spin" />
          {data.channels_backfilling} syncing
        </span>
      ) : (
        <span>all synced</span>
      )}
      {data.is_admin && (
        <button
          onClick={() => toggle.mutate()}
          disabled={toggle.isPending}
          title={data.paused ? "Resume background sync" : "Pause background sync"}
          className="ml-1 p-1 rounded-md hover:bg-card hover:text-fg transition"
        >
          {data.paused ? <Play className="w-3.5 h-3.5" /> : <Pause className="w-3.5 h-3.5" />}
        </button>
      )}
    </div>
  );
}
