import { useCallback, useEffect, useState } from 'react';
import {
  createFleetGroup,
  FLEET_GROUPS_CHANGED_EVENT,
  FLEET_GROUPS_STORAGE_KEY,
  loadFleetGroups,
  saveFleetGroups,
  type FleetGroup,
} from '../help/fleetGroups';

export function useFleetGroups() {
  const [groups, setGroups] = useState<FleetGroup[]>(() => loadFleetGroups());

  const refresh = useCallback(() => {
    setGroups(loadFleetGroups());
  }, []);

  useEffect(() => {
    const onChange = () => refresh();
    window.addEventListener(FLEET_GROUPS_CHANGED_EVENT, onChange);
    const onStorage = (e: StorageEvent) => {
      if (e.key === FLEET_GROUPS_STORAGE_KEY) refresh();
    };
    window.addEventListener('storage', onStorage);
    return () => {
      window.removeEventListener(FLEET_GROUPS_CHANGED_EVENT, onChange);
      window.removeEventListener('storage', onStorage);
    };
  }, [refresh]);

  const persist = useCallback((next: FleetGroup[]) => {
    saveFleetGroups(next);
    setGroups(next);
  }, []);

  const addGroup = useCallback(
    (name: string, color: string, agentIds: string[]) => {
      const g = createFleetGroup(name, color, agentIds);
      persist([...loadFleetGroups(), g]);
      return g;
    },
    [persist]
  );

  const removeGroup = useCallback(
    (id: string) => {
      persist(loadFleetGroups().filter((g) => g.id !== id));
    },
    [persist]
  );

  const updateGroupAgents = useCallback(
    (id: string, agentIds: string[]) => {
      persist(
        loadFleetGroups().map((g) =>
          g.id === id ? { ...g, agentIds: [...new Set(agentIds)] } : g
        )
      );
    },
    [persist]
  );

  return { groups, addGroup, removeGroup, updateGroupAgents, refresh };
}
