import { useCallback, useState } from 'react';

export const BOOKING_LIST_EXPANDED_KEYS = {
    technicianJobs: 'booking-list-expanded:technician-jobs',
    technicianLive: 'booking-list-expanded:technician-live',
    customerPortalBookings: 'booking-list-expanded:customer-portal',
    adminCustomerBookings: 'booking-list-expanded:admin-customer-bookings',
} as const;

export type BookingListExpandedStorageKey =
    (typeof BOOKING_LIST_EXPANDED_KEYS)[keyof typeof BOOKING_LIST_EXPANDED_KEYS];

export function getBookingListGlobalExpanded(storageKey: BookingListExpandedStorageKey): boolean {
    if (typeof window === 'undefined') {
        return false;
    }

    try {
        const value = localStorage.getItem(storageKey);

        if (value === null) {
            return false;
        }

        return value === 'true';
    } catch {
        return false;
    }
}

export function setBookingListGlobalExpanded(
    storageKey: BookingListExpandedStorageKey,
    expanded: boolean,
): void {
    try {
        localStorage.setItem(storageKey, String(expanded));
    } catch {
        // ignore storage failures
    }
}

export function useBookingListGlobalExpanded(storageKey: BookingListExpandedStorageKey) {
    const [allExpanded, setAllExpanded] = useState(() =>
        getBookingListGlobalExpanded(storageKey),
    );
    const [expandRevision, setExpandRevision] = useState(0);

    const toggleAllExpanded = useCallback(() => {
        setAllExpanded((value) => {
            const next = !value;
            setBookingListGlobalExpanded(storageKey, next);

            return next;
        });
        setExpandRevision((revision) => revision + 1);
    }, [storageKey]);

    return {
        allExpanded,
        expandRevision,
        toggleAllExpanded,
    };
}
