import { useCallback, useEffect, useRef, useState } from "react";
import { ListRooms } from "../../wailsjs/go/main/MatrixService";
import { EventsOn } from "../../wailsjs/runtime/runtime";
import type { RoomSummary, SyncEventView } from "../types";

/**
 * useMatrixRooms keeps a fresh list of joined rooms. It polls every 30s and
 * re-fetches on every relevant matrix:event so that recently active rooms
 * float to the top of the sidebar without a hard refresh.
 */
export function useMatrixRooms(enabled: boolean) {
  const [rooms, setRooms] = useState<RoomSummary[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inFlight = useRef(false);

  const refresh = useCallback(async () => {
    if (inFlight.current) return;
    inFlight.current = true;
    setLoading(true);
    try {
      const list = await ListRooms();
      setRooms(list || []);
      setError(null);
    } catch (e: any) {
      setError(String(e?.message ?? e));
    } finally {
      setLoading(false);
      inFlight.current = false;
    }
  }, []);

  useEffect(() => {
    if (!enabled) return;
    refresh();
    const interval = window.setInterval(refresh, 30_000);
    const off = EventsOn("matrix:event", (ev: SyncEventView) => {
      // Only refresh for events that may move a room in the list.
      if (
        ev?.type === "message" ||
        ev?.type === "encrypted" ||
        ev?.type === "membership"
      ) {
        refresh();
      }
    });
    return () => {
      window.clearInterval(interval);
      if (typeof off === "function") off();
    };
  }, [enabled, refresh]);

  return { rooms, loading, error, refresh };
}
