import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/one_touch_bloc/one_touch_state.dart';
import 'package:syncrow_app/features/devices/bloc/one_touch_bloc/one_touch_event.dart';
import 'package:syncrow_app/features/devices/model/device_control_model.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
import 'package:syncrow_app/features/devices/model/group_one_touch_model.dart';
import 'package:syncrow_app/features/devices/model/one_touch_model.dart';
import 'package:syncrow_app/features/devices/model/schedule_model.dart';
import 'package:syncrow_app/features/devices/model/status_model.dart';
import 'package:syncrow_app/services/api/devices_api.dart';
import 'package:syncrow_app/utils/helpers/snack_bar.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';

class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
  final String oneTouchId;
  final String switchCode;
  OneTouchModel deviceStatus = OneTouchModel(
      firstSwitch: false,
      firstCountDown: 0,
      light_mode: lightStatus.off,
      relay: status.off,
      relay_status_1: status.off);
  Timer? _timer;

  bool oneTouchGroup = false;
  List<DeviceModel> devicesList = [];

  OneTouchBloc({required this.oneTouchId, required this.switchCode})
      : super(InitialState()) {
    on<InitialEvent>(_fetchOneTouchStatus);
    on<OneTouchUpdated>(_oneTouchUpdated);
    on<ChangeFirstSwitchStatusEvent>(_changeFirstSwitch);
    on<ChangeSlidingSegment>(_changeSliding);
    on<SetCounterValue>(_setCounterValue);
    on<GetCounterEvent>(_getCounterValue);
    on<TickTimer>(_onTickTimer);
    on<OnClose>(_onClose);
    on<ToggleDaySelectionEvent>(toggleDaySelection);
    on<ScheduleSave>(saveSchedule);
    on<GetScheduleEvent>(getSchedule);
    on<ToggleScheduleEvent>(toggleChange);
    on<DeleteScheduleEvent>(deleteSchedule);
    on<ToggleSelectedEvent>(toggleSelectedIndex);
    on<ToggleCreateScheduleEvent>(toggleCreateSchedule);
    on<InitialWizardEvent>(_fetchOneTouchWizardStatus);
    on<ChangeFirstWizardSwitchStatusEvent>(_changeFirstWizardSwitch);
    on<GroupAllOnEvent>(_groupAllOn);
    on<GroupAllOffEvent>(_groupAllOff);
    on<ChangeStatusEvent>(_changeStatus);
  }

  void _fetchOneTouchStatus(
      InitialEvent event, Emitter<OneTouchState> emit) async {
    emit(LoadingInitialState());
    try {
      var response = await DevicesAPI.getDeviceStatus(oneTouchId);
      List<StatusModel> statusModelList = [];
      for (var status in response['status']) {
        statusModelList.add(StatusModel.fromJson(status));
      }
      deviceStatus = OneTouchModel.fromJson(statusModelList);
      _listenToChanges(oneTouchId);

      emit(UpdateState(oneTouchModel: deviceStatus));
    } catch (e) {
      emit(FailedState(error: e.toString()));
      return;
    }
  }

  StreamSubscription<DatabaseEvent>? _streamSubscription;
  void _listenToChanges(String id) {
    try {
      _streamSubscription?.cancel();
      DatabaseReference ref =
          FirebaseDatabase.instance.ref('device-status/$id');
      Stream<DatabaseEvent> stream = ref.onValue;

      _streamSubscription = stream.listen((DatabaseEvent event) {
        if (event.snapshot.value != null) {
          Map<dynamic, dynamic> usersMap =
              event.snapshot.value as Map<dynamic, dynamic>;
          List<StatusModel> statusList = [];

          usersMap['status'].forEach((element) {
            statusList.add(
                StatusModel(code: element['code'], value: element['value']));
          });
          var switchStatus = statusList.firstWhere(
              (status) => status.code == "switch_1",
              orElse: () => StatusModel(code: "switch_1", value: false));

          deviceStatus.firstSwitch = switchStatus.value as bool;
          add(OneTouchUpdated());
        }
      });
    } catch (_) {
    }
  }

  @override
  Future<void> close() async {
    _streamSubscription?.cancel();
    _streamSubscription = null;
    return super.close();
  }

  _oneTouchUpdated(OneTouchUpdated event, Emitter<OneTouchState> emit) {
    emit(LoadingNewSate(oneTouchModel: deviceStatus));
    emit(UpdateState(oneTouchModel: deviceStatus));
  }

  void _changeFirstSwitch(
      ChangeFirstSwitchStatusEvent event, Emitter<OneTouchState> emit) async {
    emit(LoadingNewSate(oneTouchModel: deviceStatus));
    try {
      deviceStatus.firstSwitch = !event.value;
      emit(UpdateState(oneTouchModel: deviceStatus));
      if (_timer != null) {
        _timer!.cancel();
      }
      _timer = Timer(const Duration(milliseconds: 500), () async {
        final response = await DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: oneTouchGroup ? event.deviceId : oneTouchId,
                code: 'switch_1',
                value: !event.value),
            oneTouchGroup ? event.deviceId : oneTouchId);

        if (!response['success']) {
          add(InitialEvent(groupScreen: oneTouchGroup));
        }
      });
    } catch (_) {
      add(InitialEvent(groupScreen: oneTouchGroup));
    }
  }

  void _changeSliding(
      ChangeSlidingSegment event, Emitter<OneTouchState> emit) async {
    emit(ChangeSlidingSegmentState(value: event.value));
  }

  void _setCounterValue(
      SetCounterValue event, Emitter<OneTouchState> emit) async {
    emit(LoadingNewSate(oneTouchModel: deviceStatus));
    int seconds = 0;
    try {
      seconds = event.duration.inSeconds;
      final response = await DevicesAPI.controlDevice(
          DeviceControlModel(
              deviceId: oneTouchId, code: event.deviceCode, value: seconds),
          oneTouchId);

      if (response['success'] ?? false) {
        if (event.deviceCode == 'countdown_1') {
          deviceStatus.firstCountDown = seconds;
        }
      } else {
        emit(const FailedState(error: 'Something went wrong'));
        return;
      }
    } catch (e) {
      emit(FailedState(error: e.toString()));
      return;
    }
    if (seconds > 0) {
      _onStartTimer(seconds);
    } else {
      _timer?.cancel();
      emit(TimerRunComplete());
    }
  }

  void _getCounterValue(
      GetCounterEvent event, Emitter<OneTouchState> emit) async {
    emit(LoadingInitialState());
    try {
      var response = await DevicesAPI.getDeviceStatus(oneTouchId);
      List<StatusModel> statusModelList = [];
      for (var status in response['status']) {
        statusModelList.add(StatusModel.fromJson(status));
      }
      deviceStatus = OneTouchModel.fromJson(statusModelList);

      if (event.deviceCode == 'countdown_1') {
        deviceStatus.firstCountDown > 0
            ? _onStartTimer(deviceStatus.firstCountDown)
            : emit(UpdateTimerState(seconds: deviceStatus.firstCountDown));
      }
    } catch (e) {
      emit(FailedState(error: e.toString()));
      return;
    }
  }

  void _onClose(OnClose event, Emitter<OneTouchState> emit) {
    _timer?.cancel();
  }

  void _onStartTimer(int seconds) {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      add(TickTimer(seconds - timer.tick));
    });
  }

  void _onTickTimer(TickTimer event, Emitter<OneTouchState> emit) {
    if (event.remainingTime > 0) {
      emit(TimerRunInProgress(event.remainingTime));
    } else {
      _timer?.cancel();
      emit(TimerRunComplete());
    }
  }

  List<Map<String, String>> days = [
    {"day": "Sun", "key": "Sun"},
    {"day": "Mon", "key": "Mon"},
    {"day": "Tue", "key": "Tue"},
    {"day": "Wed", "key": "Wed"},
    {"day": "Thu", "key": "Thu"},
    {"day": "Fri", "key": "Fri"},
    {"day": "Sat", "key": "Sat"},
  ];

  Future<void> saveSchedule(
    ScheduleSave event,
    Emitter<OneTouchState> emit,
  ) async {
    try {
      if (selectedDays.isNotEmpty) {
        emit(LoadingInitialState());
        await DevicesAPI.postSchedule(
            category: switchCode,
            deviceId: oneTouchId,
            time: getTimeStampWithoutSeconds(selectedTime).toString(),
            code: switchCode,
            value: toggleSchedule,
            days: selectedDays);
        CustomSnackBar.displaySnackBar('Save Successfully');
        add(GetScheduleEvent());
        emit(SaveSchedule());

        add(const ToggleCreateScheduleEvent(index: 1));
      } else {
        CustomSnackBar.displaySnackBar('Please select days');
      }
    } catch (e) {
      emit(FailedState(error: e.toString()));
    }
  }

  Future<void> getSchedule(
    GetScheduleEvent event,
    Emitter<OneTouchState> emit,
  ) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.getSchedule(
        category: switchCode,
        deviceId: oneTouchId,
      );
      List<dynamic> jsonData = response;
      listSchedule =
          jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
      emit(InitialState());
    } on DioException catch (e) {
      final errorData = e.response!.data;
      String errorMessage = errorData['message'];
      emit(FailedState(error: errorMessage.toString()));
    }
  }

  int? getTimeStampWithoutSeconds(DateTime? dateTime) {
    if (dateTime == null) return null;
    DateTime dateTimeWithoutSeconds = DateTime(dateTime.year, dateTime.month,
        dateTime.day, dateTime.hour, dateTime.minute);
    return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000;
  }

  Future toggleChange(
      ToggleScheduleEvent event, Emitter<OneTouchState> emit) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.changeSchedule(
          scheduleId: event.id, deviceUuid: oneTouchId, enable: event.toggle);
      if (response == true) {
        add(GetScheduleEvent());
        toggleSchedule = event.toggle;
        return toggleSchedule;
      }
      emit(IsToggleState(onOff: toggleSchedule));
      add(const ChangeSlidingSegment(value: 1));
    } on DioException catch (e) {
      final errorData = e.response!.data;
      String errorMessage = errorData['message'];
      emit(FailedState(error: errorMessage.toString()));
    }
  }

  Future deleteSchedule(
      DeleteScheduleEvent event, Emitter<OneTouchState> emit) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.deleteSchedule(
        scheduleId: event.id,
        deviceUuid: oneTouchId,
      );
      if (response == true) {
        add(GetScheduleEvent());
        return toggleSchedule;
      }
      emit(IsToggleState(onOff: toggleSchedule));
      add(const ChangeSlidingSegment(value: 1));
    } on DioException catch (e) {
      final errorData = e.response!.data;
      String errorMessage = errorData['message'];
      emit(FailedState(error: errorMessage.toString()));
    }
  }

  void toggleCreateSchedule(
      ToggleCreateScheduleEvent event, Emitter<OneTouchState> emit) {
    emit(LoadingInitialState());
    createSchedule = !createSchedule;
    selectedDays.clear();
    selectedTime = DateTime.now();
    emit(UpdateCreateScheduleState(createSchedule));
  }

  bool toggleSchedule = true;
  List<String> selectedDays = [];
  bool createSchedule = false;
  List<ScheduleModel> listSchedule = [];
  DateTime? selectedTime = DateTime.now();
  Future<void> toggleDaySelection(
    ToggleDaySelectionEvent event,
    Emitter<OneTouchState> emit,
  ) async {
    emit(LoadingInitialState());
    if (selectedDays.contains(event.key)) {
      selectedDays.remove(event.key);
    } else {
      selectedDays.add(event.key);
    }
    emit(ChangeTimeState());
    add(ChangeSlidingSegment(value: 1));
  }

  int selectedTabIndex = 0;

  void toggleSelectedIndex(
      ToggleSelectedEvent event, Emitter<OneTouchState> emit) {
    emit(LoadingInitialState());
    selectedTabIndex = event.index;
    emit(ChangeSlidingSegmentState(value: selectedTabIndex));
  }

  List<GroupOneTouchModel> groupOneTouchList = [];
  bool allSwitchesOn = true;

  void _fetchOneTouchWizardStatus(
      InitialWizardEvent event, Emitter<OneTouchState> emit) async {
    emit(LoadingInitialState());
    try {
      devicesList = [];
      groupOneTouchList = [];
      allSwitchesOn = true;
      devicesList = await DevicesAPI.getDeviceByGroupName(
          HomeCubit.getInstance().selectedSpace?.id ?? '', '1GT');

      for (int i = 0; i < devicesList.length; i++) {
        var response =
            await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
        List<StatusModel> statusModelList = [];
        for (var status in response['status']) {
          statusModelList.add(StatusModel.fromJson(status));
        }
        deviceStatus = OneTouchModel.fromJson(statusModelList);
        groupOneTouchList.add(GroupOneTouchModel(
          deviceId: devicesList[i].uuid ?? '',
          deviceName: devicesList[i].name ?? '',
          firstSwitch: deviceStatus.firstSwitch,
        ));
      }

      if (groupOneTouchList.isNotEmpty) {
        groupOneTouchList.firstWhere((element) {
          if (!element.firstSwitch) {
            allSwitchesOn = false;
          }
          return true;
        });
      }
      emit(UpdateGroupState(
          oneTouchList: groupOneTouchList, allSwitches: allSwitchesOn));
    } catch (e) {
      emit(FailedState(error: e.toString()));
      return;
    }
  }

  void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event,
      Emitter<OneTouchState> emit) async {
    emit(LoadingNewSate(oneTouchModel: deviceStatus));
    try {
      bool allSwitchesValue = true;
      groupOneTouchList.forEach((element) {
        if (element.deviceId == event.deviceId) {
          element.firstSwitch = !event.value;
        }
        if (!element.firstSwitch) {
          allSwitchesValue = false;
        }
      });
      final response = await DevicesAPI.deviceBatchController(
        code: 'switch_1',
        devicesUuid: [event.deviceId],
        value: !event.value,
      );

      emit(UpdateGroupState(
          oneTouchList: groupOneTouchList, allSwitches: allSwitchesValue));
      if (response['success']) {
        add(InitialEvent(groupScreen: oneTouchGroup));
      }
    } catch (_) {
      add(InitialEvent(groupScreen: oneTouchGroup));
    }
  }

  void _groupAllOn(GroupAllOnEvent event, Emitter<OneTouchState> emit) async {
    emit(LoadingNewSate(oneTouchModel: deviceStatus));
    try {
      // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off)
      for (int i = 0; i < groupOneTouchList.length; i++) {
        groupOneTouchList[i].firstSwitch = true;
      }

      // Emit the state with updated values
      emit(
          UpdateGroupState(oneTouchList: groupOneTouchList, allSwitches: true));

      // Get a list of all device IDs
      List<String> allDeviceIds =
          groupOneTouchList.map((device) => device.deviceId).toList();

      // First call for switch_1
      final response1 = await DevicesAPI.deviceBatchController(
        code: 'switch_1', // Controls first switch for all devices
        devicesUuid: allDeviceIds,
        value: true, // true (on) or false (off) depending on the event value
      );
      if (response1['failedResults'].toString() != '[]') {
        await Future.delayed(const Duration(milliseconds: 500));
        add(const InitialEvent(groupScreen: true));
      }
    } catch (_) {
      emit(FailedState(error: _.toString()));
      // In case of an error, delay and reset the screen to initial state
      await Future.delayed(const Duration(milliseconds: 500));
      add(const InitialEvent(groupScreen: true));
    }
  }

  void _groupAllOff(GroupAllOffEvent event, Emitter<OneTouchState> emit) async {
    emit(LoadingNewSate(oneTouchModel: deviceStatus));
    try {
      // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off)
      for (int i = 0; i < groupOneTouchList.length; i++) {
        groupOneTouchList[i].firstSwitch = false;
      }

      // Emit the state with updated values
      emit(UpdateGroupState(
          oneTouchList: groupOneTouchList, allSwitches: false));

      // Get a list of all device IDs
      List<String> allDeviceIds =
          groupOneTouchList.map((device) => device.deviceId).toList();

      // First call for switch_1
      final response1 = await DevicesAPI.deviceBatchController(
        code: 'switch_1', // Controls first switch for all devices
        devicesUuid: allDeviceIds,
        value: false, // true (on) or false (off) depending on the event value
      );

      // Check if either response is unsuccessful, then reset to initial state
      if (response1['failedResults'].toString() != '[]') {
        await Future.delayed(const Duration(milliseconds: 500));
        add(const InitialEvent(groupScreen: true));
      }
    } catch (_) {
      emit(FailedState(error: _.toString()));
      await Future.delayed(const Duration(milliseconds: 500));
      add(const InitialEvent(groupScreen: true));
    }
  }

  String statusSelected = '';
  String optionSelected = '';

  Future<void> _changeStatus(
      ChangeStatusEvent event, Emitter<OneTouchState> emit) async {
    try {
      emit(LoadingInitialState());

      final Map<String, Map<String, String>> controlMap = {
        "relay_status": {
          'Power On': 'power_on',
          'Power Off': 'power_off',
          'Restart Memory': 'last',
        },
        "light_mode": {
          'Off': 'none',
          'On/Off Status': 'relay',
          'Switch Position': 'pos',
        },
        "relay_status_1": {
          'Power On': 'power_on',
          'Power Off': 'power_off',
          'Restart Memory': 'last',
        },
      };

      final selectedControl = controlMap[optionSelected]?[statusSelected];
      if (selectedControl != null) {
        await DevicesAPI.controlDevice(
          DeviceControlModel(
              deviceId: oneTouchId,
              code: optionSelected,
              value: selectedControl),
          oneTouchId,
        );
      } else {
        debugPrint('Invalid statusSelected or optionSelected');
      }
    } on DioException catch (e) {
      final errorData = e.response!.data;
      String errorMessage = errorData['message'];
      emit(FailedState(error: errorMessage.toString()));
    }
  }
}
