import { useState } from 'react';
import { RotateCw } from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { useClient } from 'hooks/useClient';
import { useCapabilities } from 'hooks/useCapabilities';

type RescanResponse = { ok: boolean; counts: Record<string, number> };

// Item query caches the header refreshes after a rescan (matches the queryKeys used by the
// Automation and Capability pages).
const ITEM_QUERY_KEYS = ['tasks', 'task-categories', 'skills', 'tools', 'processes', 'agents', 'agent-categories'];

export function RescanButton() {
  const client = useClient();
  const qc = useQueryClient();
  const { can } = useCapabilities();
  const [loading, setLoading] = useState(false);

  // `POST /api/rescan` belongs to the `items` capability — skills, tools, agents and processes on the
  // owner's disk, `kind: 'execution'`. A member pressing this got a 403 and a red toast about a feature
  // whose existence is not their business.
  if (!can('items')) return null;

  const rescan = async () => {
    if (loading) return;
    setLoading(true);
    try {
      const res = await client.post<RescanResponse>('/rescan', {});
      // refetchType: 'all' so INACTIVE (unmounted) item lists refetch too — otherwise a rescan from
      // anywhere but the Tasks/Skills/… page only marks them stale, and the change isn't picked up until
      // you next open that page. This refreshes every item cache immediately, wherever you press it.
      await Promise.all(ITEM_QUERY_KEYS.map((key) => qc.invalidateQueries({ queryKey: [key], refetchType: 'all' })));
      const c = res.counts ?? {};
      toast.success(
        `Rescanned items — ${c.tasks ?? 0} tasks, ${c.agents ?? 0} agents, ${c.tools ?? 0} tools, ${c.skills ?? 0} skills, ${c.processes ?? 0} processes`,
      );
    } catch {
      toast.error('Failed to rescan items');
    } finally {
      setLoading(false);
    }
  };

  return (
    <button
      onClick={rescan}
      disabled={loading}
      className="flex h-8 w-8 items-center justify-center rounded-full bg-black/20 text-duck-dark transition-transform hover:scale-110 disabled:opacity-50"
      aria-label="Rescan items"
      title="Rescan officer-items (apply changes without restarting)"
    >
      <RotateCw size={16} className={loading ? 'animate-spin' : ''} />
    </button>
  );
}
