// BLE Context - Global state for Bluetooth management

import React, { createContext, useContext, useState, useCallback, useEffect, ReactNode } from 'react';
import { bleManager, WPDevice, WiFiNetwork, WiFiStatus, isBLEAvailable, checkBLEReadiness, BulkOperationResult, BulkWiFiResult } from '@/services/ble';
import { setOnLogoutBLECleanupCallback } from '@/services/api';
import { BleManager } from 'react-native-ble-plx';

interface BLEContextType {
  // State
  foundDevices: WPDevice[];
  isScanning: boolean;
  connectedDevices: Set<string>;
  isBLEAvailable: boolean;
  error: string | null;
  permissionError: boolean; // true if error is related to permissions

  // Actions
  scanDevices: () => Promise<void>;
  stopScan: () => void;
  connectDevice: (deviceId: string) => Promise<boolean>;
  disconnectDevice: (deviceId: string) => Promise<void>;
  getWiFiList: (deviceId: string) => Promise<WiFiNetwork[]>;
  setWiFi: (deviceId: string, ssid: string, password: string) => Promise<boolean>;
  getCurrentWiFi: (deviceId: string) => Promise<WiFiStatus | null>;
  rebootDevice: (deviceId: string) => Promise<void>;
  cleanupBLE: () => Promise<void>;
  clearError: () => void;
  checkPermissions: () => Promise<boolean>; // Manual permission check with UI prompts

  // Bulk operations
  bulkDisconnect: (deviceIds: string[]) => Promise<BulkOperationResult[]>;
  bulkReboot: (deviceIds: string[]) => Promise<BulkOperationResult[]>;
  bulkSetWiFi: (
    devices: Array<{ id: string; name: string }>,
    ssid: string,
    password: string,
    onProgress?: (deviceId: string, status: 'connecting' | 'configuring' | 'rebooting' | 'success' | 'error', error?: string) => void
  ) => Promise<BulkWiFiResult[]>;
}

const BLEContext = createContext<BLEContextType | undefined>(undefined);

export function BLEProvider({ children }: { children: ReactNode }) {
  const [foundDevices, setFoundDevices] = useState<WPDevice[]>([]);
  const [isScanning, setIsScanning] = useState(false);
  const [connectedDevices, setConnectedDevices] = useState<Set<string>>(new Set());
  const [error, setError] = useState<string | null>(null);
  const [permissionError, setPermissionError] = useState(false);

  // Lazy BleManager instance for permission checks
  const [bleManagerInstance] = useState(() => new BleManager());

  const isPermissionError = (errorMessage: string): boolean => {
    const permissionKeywords = [
      'permission',
      'unauthorized',
      'not granted',
      'denied',
      'bluetooth is disabled',
      'enable it in settings',
    ];
    const lowerMessage = errorMessage.toLowerCase();
    return permissionKeywords.some(keyword => lowerMessage.includes(keyword));
  };

  const checkPermissions = useCallback(async (): Promise<boolean> => {
    try {
      setError(null);
      setPermissionError(false);
      const ready = await checkBLEReadiness(bleManagerInstance);
      return ready;
    } catch {
      const errorMsg = 'Failed to check Bluetooth permissions';
      setError(errorMsg);
      setPermissionError(true);
      return false;
    }
  }, [bleManagerInstance]);

  const scanDevices = useCallback(async () => {
    try {
      setError(null);
      setPermissionError(false);
      setIsScanning(true);
      const devices = await bleManager.scanDevices();
      // Sort by RSSI (strongest first)
      const sorted = devices.sort((a, b) => b.rssi - a.rssi);
      setFoundDevices(sorted);
    } catch (err: any) {
      const errorMsg = err.message || 'Failed to scan for devices';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      throw err;
    } finally {
      setIsScanning(false);
    }
  }, []);

  const stopScan = useCallback(() => {
    bleManager.stopScan();
    setIsScanning(false);
  }, []);

  const connectDevice = useCallback(async (deviceId: string): Promise<boolean> => {
    try {
      setError(null);
      setPermissionError(false);
      const success = await bleManager.connectDevice(deviceId);
      if (success) {
        setConnectedDevices(prev => new Set(prev).add(deviceId));
      } else {
        // Connection failed but no exception - set user-friendly error
        const errorMsg = 'Could not connect to sensor. Please move closer and try again.';
        setError(errorMsg);
        setPermissionError(false);
      }
      return success;
    } catch (err: any) {
      const errorMsg = err.message || 'Failed to connect to device';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      return false;
    }
  }, []);

  const disconnectDevice = useCallback(async (deviceId: string): Promise<void> => {
    try {
      await bleManager.disconnectDevice(deviceId);
      setConnectedDevices(prev => {
        const next = new Set(prev);
        next.delete(deviceId);
        return next;
      });
    } catch (err: any) {
      setError(err.message || 'Failed to disconnect device');
    }
  }, []);

  const getWiFiList = useCallback(async (deviceId: string): Promise<WiFiNetwork[]> => {
    try {
      setError(null);
      const networks = await bleManager.getWiFiList(deviceId);
      return networks;
    } catch (err: any) {
      setError(err.message || 'Failed to get WiFi networks');
      throw err;
    }
  }, []);

  const setWiFi = useCallback(
    async (deviceId: string, ssid: string, password: string): Promise<boolean> => {
      try {
        setError(null);
        return await bleManager.setWiFi(deviceId, ssid, password);
      } catch (err: any) {
        setError(err.message || 'Failed to configure WiFi');
        throw err;
      }
    },
    []
  );

  const getCurrentWiFi = useCallback(
    async (deviceId: string): Promise<WiFiStatus | null> => {
      try {
        setError(null);
        return await bleManager.getCurrentWiFi(deviceId);
      } catch (err: any) {
        setError(err.message || 'Failed to get current WiFi');
        throw err;
      }
    },
    []
  );

  const rebootDevice = useCallback(async (deviceId: string): Promise<void> => {
    try {
      setError(null);
      await bleManager.rebootDevice(deviceId);
      // Remove from connected devices
      setConnectedDevices(prev => {
        const next = new Set(prev);
        next.delete(deviceId);
        return next;
      });
    } catch (err: any) {
      setError(err.message || 'Failed to reboot device');
      throw err;
    }
  }, []);

  const clearError = useCallback(() => {
    setError(null);
    setPermissionError(false);
  }, []);

  const cleanupBLE = useCallback(async () => {
    try {

      // Stop any ongoing scan
      if (isScanning) {
        stopScan();
      }

      // Cleanup via bleManager (disconnects all devices)
      await bleManager.cleanup();

      // Clear context state
      setFoundDevices([]);
      setConnectedDevices(new Set());
      setError(null);

    } catch {
      // Don't throw - we want to allow logout to proceed even if BLE cleanup fails
    }
  }, [isScanning, stopScan]);

  // Bulk operations
  const bulkDisconnect = useCallback(async (deviceIds: string[]): Promise<BulkOperationResult[]> => {
    try {
      setError(null);
      setPermissionError(false);
      const results = await bleManager.bulkDisconnect(deviceIds);
      // Update connected devices set
      const successfulDisconnects = results.filter(r => r.success).map(r => r.deviceId);
      if (successfulDisconnects.length > 0) {
        setConnectedDevices(prev => {
          const next = new Set(prev);
          successfulDisconnects.forEach(id => next.delete(id));
          return next;
        });
      }
      return results;
    } catch (err: any) {
      const errorMsg = err.message || 'Bulk disconnect failed';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      throw err;
    }
  }, []);

  const bulkReboot = useCallback(async (deviceIds: string[]): Promise<BulkOperationResult[]> => {
    try {
      setError(null);
      setPermissionError(false);
      const results = await bleManager.bulkReboot(deviceIds);
      // Devices that were rebooted are no longer connected
      const successfulReboots = results.filter(r => r.success).map(r => r.deviceId);
      if (successfulReboots.length > 0) {
        setConnectedDevices(prev => {
          const next = new Set(prev);
          successfulReboots.forEach(id => next.delete(id));
          return next;
        });
      }
      return results;
    } catch (err: any) {
      const errorMsg = err.message || 'Bulk reboot failed';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      throw err;
    }
  }, []);

  const bulkSetWiFi = useCallback(async (
    devices: Array<{ id: string; name: string }>,
    ssid: string,
    password: string,
    onProgress?: (deviceId: string, status: 'connecting' | 'configuring' | 'rebooting' | 'success' | 'error', error?: string) => void
  ): Promise<BulkWiFiResult[]> => {
    try {
      setError(null);
      setPermissionError(false);
      const results = await bleManager.bulkSetWiFi(devices, ssid, password, onProgress);
      // Update connected devices - successful setups result in reboots (disconnected)
      const successfulSetups = results.filter(r => r.success).map(r => r.deviceId);
      if (successfulSetups.length > 0) {
        setConnectedDevices(prev => {
          const next = new Set(prev);
          successfulSetups.forEach(id => next.delete(id));
          return next;
        });
      }
      return results;
    } catch (err: any) {
      const errorMsg = err.message || 'Bulk WiFi configuration failed';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      throw err;
    }
  }, []);

  // Register BLE cleanup callback for logout
  useEffect(() => {
    setOnLogoutBLECleanupCallback(cleanupBLE);

    return () => {
      setOnLogoutBLECleanupCallback(null);
    };
  }, [cleanupBLE]);

  const value: BLEContextType = {
    foundDevices,
    isScanning,
    connectedDevices,
    isBLEAvailable,
    error,
    permissionError,
    scanDevices,
    stopScan,
    connectDevice,
    disconnectDevice,
    getWiFiList,
    setWiFi,
    getCurrentWiFi,
    rebootDevice,
    cleanupBLE,
    clearError,
    checkPermissions,
    bulkDisconnect,
    bulkReboot,
    bulkSetWiFi,
  };

  return <BLEContext.Provider value={value}>{children}</BLEContext.Provider>;
}

export function useBLE() {
  const context = useContext(BLEContext);
  if (context === undefined) {
    throw new Error('useBLE must be used within a BLEProvider');
  }
  return context;
}
