/**
 * useDeviceMenuItems
 * ==================
 * Fetches active devices and returns them as sidebar nav children
 * for the Access Logs menu group — fully dynamic, no hardcoding.
 *
 * Usage in MenuItems.ts:
 *   Import the hook and call it in a client component to get the
 *   dynamic children, then merge into the static menu structure.
 */

import { useEffect, useState } from "react";
import axios from "axios";
import { uniqueId } from "lodash";
import { IconPoint } from "@tabler/icons-react";
import { getSession } from "@/utils/sessionData";

export interface DeviceNavItem {
    id: string;
    title: string;
    icon: typeof IconPoint;
    href: string;
}

export function useDeviceMenuItems() {
    const [items, setItems] = useState<DeviceNavItem[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const session = getSession();
        if (!session?.token) { setLoading(false); return; }

        axios.post("/api/getDevices", { token: session.token })
            .then((res) => {
                if (res.data.status !== "error") {
                    const devs: any[] = res.data.devices ?? [];
                    setItems(
                        devs.map((d) => ({
                            id: uniqueId(),
                            title: d.location ? `${d.name} — ${d.location}` : d.name,
                            icon: IconPoint,
                            href: `/accessLog?deviceId=${d.id}&deviceKey=${encodeURIComponent(d.deviceKey ?? "")}`,
                        }))
                    );
                }
            })
            .catch(() => { }) // non-fatal — sidebar still renders without children
            .finally(() => setLoading(false));
    }, []);

    return { items, loading };
}