"use client";

import {
  createContext,
  useContext,
  useReducer,
  useMemo,
  useEffect,
  useCallback,
  useRef,
} from "react";
import { formatDistanceToNowStrict } from "date-fns";
import { useAuth } from "./AuthProvider";
import {
  loadDashboardData as loadDashboardDataSS,
  deleteDevice,
  createDeviceServerAction,
  renameDeviceName,
  sendDeviceInstructionsServerAction,
  switchStatus,
  switchResetConnection as switchResetConnectionSS,
  clearDeviceLogs as clearDeviceLogsSS,
} from "./GuardProviderSS";

// --- TYPES ---
export type Rule = {
  id: string;
  deviceId: string;
  type: "custom_url" | "preset";
  value: string;
  schedule: string;
};

export type Device = {
  id: string;
  deviceId: string;
  deviceName: string;
  assigningCode?: string | null;
  restrictedCategoryIds: string;
  rules: Rule[];
  syncStatus: boolean;
  resetConnection: boolean;
  sound: number;
  createdAt: Date;
  lastOnline: Date | null;
  deviceLog: string[];
};

export type Preset = { name: string; url: string };
export type RestrictedCategory = { id: number; label: string; urls: string };

type DashboardState = {
  devices: Device[];
  presets: Preset[];
  categories: RestrictedCategory[];
  resourcesLoaded: boolean;
  devicesLoaded: boolean;
  hasInitialized: boolean;
  isUpdating: boolean;
};

type DashboardAction =
  | {
      type: "SET_RESOURCES";
      payload: { presets: Preset[]; categories: RestrictedCategory[] };
    }
  | { type: "SET_RESOURCES_LOADED"; payload: boolean }
  | { type: "SET_DEVICES_LOADED"; payload: boolean }
  | { type: "SET_INITIALIZED"; payload: boolean }
  | { type: "SET_UPDATING"; payload: boolean }
  | { type: "ADD_DEVICE"; payload: Device }
  | { type: "REMOVE_DEVICE"; payload: string }
  | {
      type: "MODIFY_DEVICE";
      payload: { deviceId: string; changes: Partial<Device> };
    }
  | { type: "SET_DEVICE_RULE"; payload: { deviceId: string; rules: Rule[] } }
  | { type: "SET_ALL_DEVICES"; payload: Device[] };

interface DashboardContextType {
  devices: Device[];
  presets: Preset[];
  categories: RestrictedCategory[];
  resourcesLoaded: boolean;
  devicesLoaded: boolean;
  hasInitialized: boolean;
  isUpdating: boolean;

  // Enhanced Device Access Utilities
  getDevice: (deviceId: string) => Device | undefined;
  getDeviceRules: (deviceId: string) => Rule[];
  getDeviceInstructions: (deviceId: string) => {
    resetConnection: boolean;
    sound: number;
    createdAt: Date;
    lastOnline: Date | null;
  } | null;
  getDeviceLogs: (deviceId: string) => string[];
  isDeviceOnline: (deviceId: string) => boolean;
  getLastOnlineText: (deviceId: string) => string;

  // Legacy compatibility (for backward compatibility during migration)
  rulesByDevice: Record<string, Rule[]>;
  deviceInstructionsById: Record<
    string,
    {
      resetConnection: boolean;
      sound: number;
      createdAt: Date;
      lastOnline: Date | null;
    }
  >;

  // Actions
  loadResources: () => Promise<void>;
  loadDashboardData: () => Promise<void>;
  removeDevice: (deviceId: string) => Promise<boolean>;
  createDevice: (deviceName: string) => Promise<boolean>;
  refreshData: () => Promise<void>;
  refreshDataSilently: () => Promise<void>;
  updateDeviceStatus: (
    deviceId: string,
    newStatus: boolean
  ) => Promise<boolean>;
  switchResetConnection: (
    deviceId: string,
    resetConnection: boolean
  ) => Promise<boolean>;
  renameDevice: (
    deviceId: string,
    newName: string
  ) => Promise<{ success: true } | { success: false; error: string }>;
  sendDeviceInstructions: (
    deviceId: string,
    assignCode: string
  ) => Promise<{ success: true } | { success: false; error: string }>;

  // Enhanced Device Actions
  addDeviceRule: (deviceId: string, rule: Omit<Rule, "id">) => Promise<boolean>;
  updateDeviceRule: (
    deviceId: string,
    ruleId: string,
    updates: Partial<Rule>
  ) => Promise<boolean>;
  removeDeviceRule: (deviceId: string, ruleId: string) => Promise<boolean>;
  updateDeviceCategories: (
    deviceId: string,
    categoryIds: number[]
  ) => Promise<boolean>;
  updateDeviceSound: (deviceId: string, sound: number) => Promise<boolean>;
  addDeviceLog: (deviceId: string, message: string) => Promise<boolean>;
  clearDeviceLogs: (deviceId: string) => Promise<boolean>;
}

// --- REDUCER ---
const reducer = (
  state: DashboardState,
  action: DashboardAction
): DashboardState => {
  switch (action.type) {
    case "SET_RESOURCES":
      return {
        ...state,
        presets: action.payload.presets,
        categories: action.payload.categories,
        resourcesLoaded: true,
      };
    case "SET_RESOURCES_LOADED":
      return { ...state, resourcesLoaded: action.payload };
    case "SET_DEVICES_LOADED":
      return { ...state, devicesLoaded: action.payload };
    case "SET_INITIALIZED":
      return { ...state, hasInitialized: action.payload };
    case "SET_UPDATING":
      return { ...state, isUpdating: action.payload };
    case "ADD_DEVICE":
      return {
        ...state,
        devices: [...state.devices, action.payload],
      };
    case "REMOVE_DEVICE":
      return {
        ...state,
        devices: state.devices.filter((d) => d.deviceId !== action.payload),
      };
    case "MODIFY_DEVICE":
      return {
        ...state,
        devices: state.devices.map((d) =>
          d.deviceId === action.payload.deviceId
            ? { ...d, ...action.payload.changes }
            : d
        ),
      };
    case "SET_DEVICE_RULE":
      return {
        ...state,
        devices: state.devices.map((d) =>
          d.deviceId === action.payload.deviceId
            ? { ...d, rules: action.payload.rules }
            : d
        ),
      };
    case "SET_ALL_DEVICES":
      return {
        ...state,
        devices: action.payload,
        devicesLoaded: true,
      };
    default:
      return state;
  }
};

// --- CONTEXT ---
const DashboardContext = createContext<DashboardContextType>({
  devices: [],
  presets: [],
  categories: [],
  resourcesLoaded: false,
  devicesLoaded: false,
  hasInitialized: false,
  isUpdating: false,

  // Enhanced Device Access Utilities
  getDevice: () => undefined,
  getDeviceRules: () => [],
  getDeviceInstructions: () => null,
  getDeviceLogs: () => [],
  isDeviceOnline: () => false,
  getLastOnlineText: () => "Device not found",

  // Legacy compatibility
  rulesByDevice: {},
  deviceInstructionsById: {},

  // Actions
  loadResources: async () => {},
  loadDashboardData: async () => {},
  removeDevice: async () => false,
  createDevice: async () => false,
  refreshData: async () => {},
  refreshDataSilently: async () => {},
  updateDeviceStatus: async () => false,
  switchResetConnection: async () => false,
  renameDevice: async () => ({ success: false, error: "Not implemented" }),
  sendDeviceInstructions: async () => ({
    success: false,
    error: "Not implemented",
  }),

  // Enhanced Device Actions
  addDeviceRule: async () => false,
  updateDeviceRule: async () => false,
  removeDeviceRule: async () => false,
  updateDeviceCategories: async () => false,
  updateDeviceSound: async () => false,
  addDeviceLog: async () => false,
  clearDeviceLogs: async () => false,
});

export const useDashboard = () => useContext(DashboardContext);

// --- PROVIDER ---
export const DashboardDataProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const { isAuthenticated, clearSession, hasTriggeredGlobalLoad } = useAuth();

  const [state, dispatch] = useReducer(reducer, {
    devices: [],
    presets: [],
    categories: [],
    resourcesLoaded: false,
    devicesLoaded: false,
    hasInitialized: false,
    isUpdating: false,
  });

  // Cache for resources with 24-hour expiry
  const resourcesCacheRef = useRef<{
    data: { presets: Preset[]; categories: RestrictedCategory[] } | null;
    timestamp: number;
  }>({ data: null, timestamp: 0 });

  // Ref to track current state without causing rerenders
  const stateRef = useRef(state);
  stateRef.current = state;

  /**
   * Simple data comparison function
   */
  const isDataEqual = (obj1: unknown, obj2: unknown): boolean => {
    return JSON.stringify(obj1) === JSON.stringify(obj2);
  };

  /**
   * Enhanced Device Access Utilities - Memoized for performance
   */
  const getDevice = useCallback(
    (deviceId: string): Device | undefined => {
      return state.devices.find((d) => d.deviceId === deviceId);
    },
    [state.devices]
  );

  const getDeviceRules = useCallback(
    (deviceId: string): Rule[] => {
      const device = state.devices.find((d) => d.deviceId === deviceId);
      return device?.rules || [];
    },
    [state.devices]
  );

  const getDeviceInstructions = useCallback(
    (deviceId: string) => {
      const device = state.devices.find((d) => d.deviceId === deviceId);
      if (!device) return null;
      return {
        resetConnection: device.resetConnection,
        sound: device.sound,
        createdAt: device.createdAt,
        lastOnline: device.lastOnline,
      };
    },
    [state.devices]
  );

  const getDeviceLogs = useCallback(
    (deviceId: string): string[] => {
      const device = state.devices.find((d) => d.deviceId === deviceId);
      return device?.deviceLog || [];
    },
    [state.devices]
  );

  const isDeviceOnline = useCallback(
    (deviceId: string): boolean => {
      const device = state.devices.find((d) => d.deviceId === deviceId);
      if (!device?.lastOnline) return false;
      const lastOnlineMs = device.lastOnline.getTime();
      return Date.now() - lastOnlineMs < 6 * 60 * 1000; // 6 minutes
    },
    [state.devices]
  );

  const getLastOnlineText = useCallback(
    (deviceId: string): string => {
      const device = state.devices.find((d) => d.deviceId === deviceId);
      if (!device) return "Device not found";

      const lastOnlineMs = device.lastOnline?.getTime();
      const isOnline =
        lastOnlineMs && Date.now() - lastOnlineMs < 6 * 60 * 1000;

      if (isOnline) {
        return "Online";
      }

      if (device.lastOnline) {
        return `Last active ${formatDistanceToNowStrict(
          device.lastOnline
        )} ago`;
      }

      return "Not assigned";
    },
    [state.devices]
  );

  // Legacy compatibility - computed from new structure
  const rulesByDevice = useMemo(() => {
    const result: Record<string, Rule[]> = {};
    state.devices.forEach((device) => {
      result[device.deviceId] = device.rules;
    });
    return result;
  }, [state.devices]);

  const deviceInstructionsById = useMemo(() => {
    const result: Record<
      string,
      {
        resetConnection: boolean;
        sound: number;
        createdAt: Date;
        lastOnline: Date | null;
      }
    > = {};
    state.devices.forEach((device) => {
      result[device.deviceId] = {
        resetConnection: device.resetConnection,
        sound: device.sound,
        createdAt: device.createdAt,
        lastOnline: device.lastOnline,
      };
    });
    return result;
  }, [state.devices]);

  /**
   * Unified data loading function - loads resources and devices together
   */
  const loadAllData = useCallback(async () => {
    if (!isAuthenticated) {
      console.log("[Dashboard] Not authenticated, skipping data load");
      return;
    }

    dispatch({ type: "SET_UPDATING", payload: true });

    try {
      console.log("[Dashboard] Loading all dashboard data...");

      // Load resources and devices in parallel
      const [resourcesResponse, { devices: transformedDevices }] =
        await Promise.all([
          fetch("/api/resources", { cache: "no-store" }),
          loadDashboardDataSS(),
        ]);

      // Handle resources
      if (resourcesResponse.ok) {
        const resourcesData = await resourcesResponse.json();

        // Update cache
        resourcesCacheRef.current = {
          data: {
            presets: resourcesData.presets,
            categories: resourcesData.categories,
          },
          timestamp: Date.now(),
        };

        dispatch({
          type: "SET_RESOURCES",
          payload: {
            presets: resourcesData.presets,
            categories: resourcesData.categories,
          },
        });

        console.log(
          `[Dashboard] Loaded ${
            resourcesData.presets?.length || 0
          } presets and ${resourcesData.categories?.length || 0} categories`
        );
      }

      // Always use updateDevicesWithComparison for device updates
      updateDevicesWithComparison(transformedDevices);

      // Set devices as loaded
      dispatch({ type: "SET_DEVICES_LOADED", payload: true });

      if (!stateRef.current.hasInitialized) {
        dispatch({ type: "SET_INITIALIZED", payload: true });
        console.log("[Dashboard] Dashboard data initialized");
      }
    } catch (err) {
      console.error("[Dashboard] Data loading failed:", err);
      if (
        err instanceof Error &&
        err.message.includes("User no longer exists")
      ) {
        console.log("[Dashboard] Authentication required - clearing session");
        clearSession();
      }
    } finally {
      dispatch({ type: "SET_UPDATING", payload: false });
    }
  }, [isAuthenticated, clearSession]);

  /**
   * Compare two rule arrays for changes
   */
  const compareRules = (oldRules: Rule[], newRules: Rule[]): boolean => {
    if (oldRules.length !== newRules.length) return false;

    // Sort both arrays by id for consistent comparison
    const sortedOld = [...oldRules].sort((a, b) => a.id.localeCompare(b.id));
    const sortedNew = [...newRules].sort((a, b) => a.id.localeCompare(b.id));

    for (let i = 0; i < sortedOld.length; i++) {
      const oldRule = sortedOld[i];
      const newRule = sortedNew[i];

      if (
        oldRule.id !== newRule.id ||
        oldRule.value !== newRule.value ||
        oldRule.schedule !== newRule.schedule ||
        oldRule.type !== newRule.type
      ) {
        return false;
      }
    }

    return true;
  };

  /**
   * Complex device comparison and state updates
   */
  const updateDevicesWithComparison = (newDevices: Device[]) => {
    const currentDevices = stateRef.current.devices;

    // Step 1: Remove devices that no longer exist
    const newDeviceIds = new Set(newDevices.map((d) => d.deviceId));
    const devicesToKeep = currentDevices.filter((d) =>
      newDeviceIds.has(d.deviceId)
    );

    // Step 2: Compare and update existing devices
    const updatedDevices: Device[] = [];
    const currentDeviceMap = new Map(devicesToKeep.map((d) => [d.deviceId, d]));
    let hasAnyChanges = false;

    newDevices.forEach((newDevice) => {
      const currentDevice = currentDeviceMap.get(newDevice.deviceId);

      if (!currentDevice) {
        // Step 3: Add new device
        updatedDevices.push(newDevice);
        hasAnyChanges = true;
        console.log(`[Dashboard] Adding new device: ${newDevice.deviceName}`);
        return;
      }

      // Compare device properties and update only changed ones
      let hasChanges = false;
      const changes: Partial<Device> = {};

      // Debug restrictedCategoryIds comparison
      console.log(
        `[DEBUG] Device ${newDevice.deviceName} restrictedCategoryIds comparison:`,
        {
          current: `"${currentDevice.restrictedCategoryIds}"`,
          new: `"${newDevice.restrictedCategoryIds}"`,
          equal:
            currentDevice.restrictedCategoryIds ===
            newDevice.restrictedCategoryIds,
        }
      );

      if (currentDevice.deviceName !== newDevice.deviceName) {
        changes.deviceName = newDevice.deviceName;
        hasChanges = true;
        console.log(
          `[Dashboard] Device name changed: ${currentDevice.deviceName} → ${newDevice.deviceName}`
        );
      }

      if (currentDevice.syncStatus !== newDevice.syncStatus) {
        changes.syncStatus = newDevice.syncStatus;
        hasChanges = true;
        console.log(
          `[Dashboard] Device ${newDevice.deviceName} syncStatus: ${currentDevice.syncStatus} → ${newDevice.syncStatus}`
        );
      }

      if (currentDevice.sound !== newDevice.sound) {
        changes.sound = newDevice.sound;
        hasChanges = true;
        console.log(
          `[Dashboard] Device ${newDevice.deviceName} sound: ${currentDevice.sound} → ${newDevice.sound}`
        );
      }

      if (currentDevice.resetConnection !== newDevice.resetConnection) {
        changes.resetConnection = newDevice.resetConnection;
        hasChanges = true;
        console.log(
          `[Dashboard] Device ${newDevice.deviceName} resetConnection: ${currentDevice.resetConnection} → ${newDevice.resetConnection}`
        );
      }

      if (
        currentDevice.restrictedCategoryIds !== newDevice.restrictedCategoryIds
      ) {
        changes.restrictedCategoryIds = newDevice.restrictedCategoryIds;
        hasChanges = true;
        console.log(
          `[Dashboard] Device ${newDevice.deviceName} restrictedCategoryIds changed:`,
          `"${currentDevice.restrictedCategoryIds}" → "${newDevice.restrictedCategoryIds}"`
        );
      }

      if (
        JSON.stringify(currentDevice.deviceLog) !==
        JSON.stringify(newDevice.deviceLog)
      ) {
        changes.deviceLog = newDevice.deviceLog;
        hasChanges = true;
        console.log(
          `[Dashboard] Device ${newDevice.deviceName} deviceLog updated`
        );
      }

      // Compare rules separately
      const rulesChanged = !compareRules(currentDevice.rules, newDevice.rules);
      if (rulesChanged) {
        changes.rules = newDevice.rules;
        hasChanges = true;
        console.log(`[Dashboard] Device ${newDevice.deviceName} rules changed`);
      }

      // Update lastOnline without logging (changes frequently)
      if (
        currentDevice.lastOnline?.getTime() !== newDevice.lastOnline?.getTime()
      ) {
        changes.lastOnline = newDevice.lastOnline;
        hasChanges = true;
      }

      if (hasChanges) {
        updatedDevices.push({ ...currentDevice, ...changes });
        hasAnyChanges = true;
      } else {
        updatedDevices.push(currentDevice);
      }
    });

    // Check if devices were removed
    if (currentDevices.length !== updatedDevices.length) {
      hasAnyChanges = true;
      console.log(
        `[Dashboard] Device count changed: ${currentDevices.length} → ${updatedDevices.length}`
      );
    }

    // Only update the state if there are actual changes
    if (hasAnyChanges) {
      dispatch({ type: "SET_ALL_DEVICES", payload: updatedDevices });
      console.log("[Dashboard] Devices updated due to changes");
    } else {
      console.log(
        "[Dashboard] No device changes detected, skipping state update"
      );
    }
  };

  /**
   * Load dashboard data with complex comparison logic
   */
  const loadDashboardData = useCallback(async () => {
    if (!isAuthenticated) {
      console.log("[Dashboard] Not authenticated, skipping data load");
      return;
    }

    dispatch({ type: "SET_UPDATING", payload: true });

    try {
      console.log("[Dashboard] Loading dashboard data...");

      // Use new unified query that loads all data at once
      const { devices: transformedDevices } = await loadDashboardDataSS();

      // Use complex comparison to update only changed devices
      updateDevicesWithComparison(transformedDevices);

      if (!state.hasInitialized) {
        dispatch({ type: "SET_INITIALIZED", payload: true });
        console.log("[Dashboard] Dashboard data initialized");
      }
    } catch (err) {
      console.error("[Dashboard] Dashboard data loading failed:", err);
      if (
        err instanceof Error &&
        err.message.includes("User no longer exists")
      ) {
        console.log("[Dashboard] Authentication required - clearing session");
        clearSession();
      }
    } finally {
      dispatch({ type: "SET_UPDATING", payload: false });
    }
  }, [isAuthenticated, clearSession, state.hasInitialized, state.devices]);

  // Listen for trigger from AuthProvider or initialize when conditions are met
  useEffect(() => {
    const handleTriggerLoad = () => {
      if (!isAuthenticated) {
        console.log("[Dashboard] Not authenticated, ignoring trigger");
        return;
      }

      console.log("[Dashboard] Trigger received, starting data load...");
      loadAllData();
    };

    // Listen for custom event from AuthProvider
    window.addEventListener("trigger-dashboard-load", handleTriggerLoad);

    // Also trigger on hasTriggeredGlobalLoad change (fallback/backward compatibility)
    if (isAuthenticated && hasTriggeredGlobalLoad) {
      console.log("[Dashboard] Starting initialization process...");
      handleTriggerLoad();
    }

    return () => {
      window.removeEventListener("trigger-dashboard-load", handleTriggerLoad);
    };
  }, [isAuthenticated, hasTriggeredGlobalLoad, loadAllData]);

  // Device actions
  const removeDevice = async (deviceId: string): Promise<boolean> => {
    try {
      await deleteDevice(deviceId);
      dispatch({ type: "REMOVE_DEVICE", payload: deviceId });
      return true;
    } catch (err) {
      console.error("[Dashboard] Failed to remove device:", err);
      return false;
    }
  };

  const createDevice = async (deviceName: string): Promise<boolean> => {
    const result = await createDeviceServerAction(deviceName);

    if (!result.success) {
      console.error("[Dashboard] Failed to create device:", result.error);

      if (result.shouldRedirect) {
        console.log("[Dashboard] Authentication required - clearing session");
        clearSession();
      }

      return false;
    }

    dispatch({
      type: "ADD_DEVICE",
      payload: {
        ...result.device,
        syncStatus: result.device.syncStatus ?? true,
        restrictedCategoryIds: result.device.restrictedCategoryIds ?? "",
        rules: [],
        resetConnection: false,
        sound: 50,
        createdAt: new Date(),
        lastOnline: null,
        deviceLog: [],
      },
    });
    return true;
  };

  const updateDeviceStatus = useCallback(
    async (deviceId: string, newStatus: boolean): Promise<boolean> => {
      try {
        await switchStatus(deviceId, newStatus);
        dispatch({
          type: "MODIFY_DEVICE",
          payload: { deviceId, changes: { syncStatus: newStatus } },
        });
        return true;
      } catch (err) {
        console.error("[Dashboard] Failed to update device status:", err);
        return false;
      }
    },
    []
  );

  const sendDeviceInstructions = useCallback(
    async (
      deviceId: string,
      assignCode: string
    ): Promise<{ success: true } | { success: false; error: string }> => {
      try {
        const result = await sendDeviceInstructionsServerAction(
          deviceId,
          assignCode
        );
        return result;
      } catch (err) {
        const errorMessage =
          err instanceof Error
            ? err.message
            : "Unknown error while sending instructions";
        console.error("[Dashboard] Failed to send instructions:", errorMessage);
        return { success: false, error: errorMessage };
      }
    },
    []
  );

  // Enhanced Device Actions (placeholder implementations)
  const addDeviceRule = useCallback(
    async (deviceId: string, rule: Omit<Rule, "id">): Promise<boolean> => {
      console.log("addDeviceRule not yet implemented", deviceId, rule);
      return false;
    },
    []
  );

  const updateDeviceRule = useCallback(
    async (
      deviceId: string,
      ruleId: string,
      updates: Partial<Rule>
    ): Promise<boolean> => {
      console.log(
        "updateDeviceRule not yet implemented",
        deviceId,
        ruleId,
        updates
      );
      return false;
    },
    []
  );

  const removeDeviceRule = useCallback(
    async (deviceId: string, ruleId: string): Promise<boolean> => {
      console.log("removeDeviceRule not yet implemented", deviceId, ruleId);
      return false;
    },
    []
  );

  const updateDeviceCategories = useCallback(
    async (deviceId: string, categoryIds: number[]): Promise<boolean> => {
      console.log(
        "updateDeviceCategories not yet implemented",
        deviceId,
        categoryIds
      );
      return false;
    },
    []
  );

  const updateDeviceSound = useCallback(
    async (deviceId: string, sound: number): Promise<boolean> => {
      console.log("updateDeviceSound not yet implemented", deviceId, sound);
      return false;
    },
    []
  );

  const addDeviceLog = useCallback(
    async (deviceId: string, message: string): Promise<boolean> => {
      console.log("addDeviceLog not yet implemented", deviceId, message);
      return false;
    },
    []
  );

  const clearDeviceLogs = useCallback(
    async (deviceId: string): Promise<boolean> => {
      try {
        const result = await clearDeviceLogsSS(deviceId);
        if (result.success) {
          // Clear logs from the device in state
          dispatch({
            type: "MODIFY_DEVICE",
            payload: { deviceId, changes: { deviceLog: [] } },
          });
          return true;
        }
        return false;
      } catch (err) {
        console.error("[Dashboard] Failed to clear device logs:", err);
        return false;
      }
    },
    []
  );

  const switchResetConnection = useCallback(
    async (deviceId: string, resetConnection: boolean): Promise<boolean> => {
      try {
        await switchResetConnectionSS(deviceId, resetConnection);
        dispatch({
          type: "MODIFY_DEVICE",
          payload: { deviceId, changes: { resetConnection } },
        });
        return true;
      } catch (err) {
        console.error("[Dashboard] Failed to switch reset connection:", err);
        return false;
      }
    },
    []
  );

  const renameDevice = useCallback(
    async (
      deviceId: string,
      newName: string
    ): Promise<{ success: true } | { success: false; error: string }> => {
      try {
        await renameDeviceName(deviceId, newName);
        dispatch({
          type: "MODIFY_DEVICE",
          payload: { deviceId, changes: { deviceName: newName } },
        });
        return { success: true };
      } catch (err) {
        const msg = err instanceof Error ? err.message : "Rename failed";
        return { success: false, error: msg };
      }
    },
    []
  );

  const refreshData = useCallback(async () => {
    await loadDashboardData();
  }, [loadDashboardData]);

  // Background refresh without any loading indicators - used by updater component
  const refreshDataSilently = useCallback(async () => {
    // Use current state values without adding them as dependencies
    const currentState = stateRef.current;

    if (!isAuthenticated) {
      console.log("[Dashboard] Not authenticated, skipping background refresh");
      return;
    }

    // Don't run silent refresh if initial loading is still in progress
    if (!currentState.hasInitialized) {
      console.log(
        "[Dashboard] Initial loading not complete, skipping silent refresh"
      );
      return;
    }

    // Don't run if any loading is currently in progress
    if (currentState.isUpdating) {
      console.log("[Dashboard] Loading in progress, skipping silent refresh");
      return;
    }

    console.log("[Dashboard] Silent background refresh started...");

    try {
      // Fetch fresh data without triggering loading states using unified query
      const [{ devices: transformedDevices }, resourcesData] =
        await Promise.all([
          loadDashboardDataSS(),
          currentState.presets && currentState.categories
            ? Promise.resolve({
                presets: currentState.presets,
                categories: currentState.categories,
              })
            : fetch("/api/resources", { cache: "no-store" }).then((res) =>
                res.json()
              ),
        ]);

      // Use complex comparison to update only changed devices
      updateDevicesWithComparison(transformedDevices);

      let resourcesChanged = false;
      if (!currentState.presets || !currentState.categories) {
        resourcesChanged = true;
      } else {
        const presetsChanged = !isDataEqual(
          currentState.presets,
          resourcesData.presets
        );
        const categoriesChanged = !isDataEqual(
          currentState.categories,
          resourcesData.categories
        );
        resourcesChanged = presetsChanged || categoriesChanged;
      }

      if (resourcesChanged) {
        console.log(
          "[Dashboard] Silent refresh: Resources changed, updating..."
        );
        dispatch({
          type: "SET_RESOURCES",
          payload: {
            presets: resourcesData.presets,
            categories: resourcesData.categories,
          },
        });
      }
    } catch (err) {
      console.error("[Dashboard] Silent refresh failed:", err);
    }
  }, [isAuthenticated]); // Only depend on isAuthenticated

  const contextValue = useMemo(
    () => ({
      ...state,
      // Enhanced Device Access Utilities
      getDevice,
      getDeviceRules,
      getDeviceInstructions,
      getDeviceLogs,
      isDeviceOnline,
      getLastOnlineText,
      // Legacy compatibility
      rulesByDevice,
      deviceInstructionsById,
      // Actions
      loadResources: loadAllData, // Legacy compatibility
      loadDashboardData: loadAllData,
      removeDevice,
      createDevice,
      refreshData,
      refreshDataSilently,
      updateDeviceStatus,
      switchResetConnection,
      renameDevice,
      sendDeviceInstructions,
      // Enhanced Device Actions
      addDeviceRule,
      updateDeviceRule,
      removeDeviceRule,
      updateDeviceCategories,
      updateDeviceSound,
      addDeviceLog,
      clearDeviceLogs,
    }),
    [
      state,
      // Only include stable callbacks, not the computed values that depend on state
      loadAllData,
      createDevice,
      refreshData,
      refreshDataSilently,
      updateDeviceStatus,
      switchResetConnection,
      renameDevice,
      sendDeviceInstructions,
      addDeviceRule,
      updateDeviceRule,
      removeDeviceRule,
      updateDeviceCategories,
      updateDeviceSound,
      addDeviceLog,
      clearDeviceLogs,
    ]
  );

  return (
    <DashboardContext.Provider value={contextValue}>
      {children}
    </DashboardContext.Provider>
  );
};
