"use client";

import React from "react";
import { getBranches } from "@/lib/frontend/apiClient";

export const BRANCH_LIST_STATE = Object.freeze({
	IDLE: "idle",
	LOADING: "loading",
	READY: "ready",
	ERROR: "error",
});

/**
 * useSearchBranches
 *
 * Purpose:
 * - Fetch the list of branches for admin/dev users (used by the Search multi-select UI).
 *
 * UX policy:
 * - Fail open: if loading fails, the rest of the Search UI must still work.
 * - Branch users never need this list.
 *
 * @param {{ enabled: boolean }} args
 * @returns {{ status: "idle"|"loading"|"ready"|"error", branches: string[]|null, retry: () => void }}
 */
export function useSearchBranches({ enabled }) {
	const [status, setStatus] = React.useState(
		enabled ? BRANCH_LIST_STATE.LOADING : BRANCH_LIST_STATE.IDLE
	);
	const [branches, setBranches] = React.useState(null);

	const [retryTick, setRetryTick] = React.useState(0);

	const retry = React.useCallback(() => {
		setRetryTick((n) => n + 1);
	}, []);

	React.useEffect(() => {
		if (!enabled) {
			setStatus(BRANCH_LIST_STATE.IDLE);
			setBranches(null);
			return;
		}

		let cancelled = false;

		setStatus(BRANCH_LIST_STATE.LOADING);
		setBranches(null);

		(async () => {
			try {
				const res = await getBranches();
				if (cancelled) return;

				const list = Array.isArray(res?.branches) ? res.branches : [];
				setBranches(list);
				setStatus(BRANCH_LIST_STATE.READY);
			} catch (err) {
				if (cancelled) return;

				console.error("[useSearchBranches] getBranches failed:", err);
				setBranches(null);
				setStatus(BRANCH_LIST_STATE.ERROR);
			}
		})();

		return () => {
			cancelled = true;
		};
	}, [enabled, retryTick]);

	return { status, branches, retry };
}
