import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.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/two_touch_bloc/two_touch_event.dart';
import 'package:syncrow_app/features/devices/bloc/two_touch_bloc/two_touch_state.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_two_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/features/devices/model/two_touch_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 TwoTouchBloc extends Bloc<TwoTouchEvent, TwoTouchState> {
  final String twoTouchId;
  final String switchCode;
  TwoTouchModel deviceStatus = TwoTouchModel(
    firstSwitch: false,
    secondSwitch: false,
    firstCountDown: 0,
    secondCountDown: 0,
    light_mode: lightStatus.off,
    relay: status.off,
    relay_status_1: status.off,
    relay_status_2: status.off,
  );
  Timer? _timer;

  bool twoTouchGroup = false;
  List<DeviceModel> devicesList = [];
  List<GroupTwoTouchModel> groupTwoTouchList = [];
  bool allSwitchesOn = true;
  bool toggleSchedule = true;
  List<String> selectedDays = [];

  bool createSchedule = false;
  List<ScheduleModel> listSchedule = [];

  TwoTouchBloc({required this.twoTouchId, required this.switchCode})
      : super(InitialState()) {
    on<InitialEvent>(_fetchTwoTouchStatus);
    on<TwoTouchUpdated>(_twoTouchUpdated);
    on<ChangeFirstSwitchStatusEvent>(_changeFirstSwitch);
    on<ChangeSecondSwitchStatusEvent>(_changeSecondSwitch);
    on<AllOffEvent>(_allOff);
    on<AllOnEvent>(_allOn);
    on<ChangeSlidingSegment>(_changeSliding);
    on<SetCounterValue>(_setCounterValue);
    on<GetCounterEvent>(_getCounterValue);
    on<TickTimer>(_onTickTimer);
    on<OnClose>(_onClose);
    on<GroupAllOnEvent>(_groupAllOn);
    on<GroupAllOffEvent>(_groupAllOff);
    on<ToggleDaySelectionEvent>(toggleDaySelection);
    on<TwoTouchSave>(saveSchedule);
    on<GetScheduleEvent>(getSchedule);
    on<ToggleScheduleEvent>(toggleRepeat);
    on<DeleteScheduleEvent>(deleteSchedule);
    on<ToggleSelectedEvent>(toggleSelectedIndex);
    on<ToggleCreateScheduleEvent>(toggleCreateSchedule);
    on<InitialWizardEvent>(_fetchTwoTouchWizardStatus);
    on<ChangeFirstWizardSwitchStatusEvent>(_changeFirstWizardSwitch);
    on<ChangeSecondWizardSwitchStatusEvent>(_changeSecondWizardSwitch);
    on<ChangeStatusEvent>(_changeStatus);
  }

  DateTime? selectedTime = DateTime.now();

  int selectedTabIndex = 0;

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

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

  void _fetchTwoTouchStatus(
      InitialEvent event, Emitter<TwoTouchState> emit) async {
    emit(LoadingInitialState());
    try {
      var response = await DevicesAPI.getDeviceStatus(twoTouchId);
      List<StatusModel> statusModelList = [];
      for (var status in response['status']) {
        statusModelList.add(StatusModel.fromJson(status));
      }
      deviceStatus = TwoTouchModel.fromJson(statusModelList);
      emit(UpdateState(twoTouchModel: deviceStatus));
      _listenToChanges();
    } catch (e) {
      emit(FailedState(error: e.toString()));
      return;
    }
  }

  StreamSubscription<DatabaseEvent>? _streamSubscription;

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

      _streamSubscription = stream.listen((DatabaseEvent event) async {
        if (_timer != null) {
          await Future.delayed(const Duration(seconds: 1));
        }
        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 switch1Status = statusList.firstWhere(
              (status) => status.code == "switch_1",
              orElse: () => StatusModel(code: "switch_1", value: false));

          var switch2Status = statusList.firstWhere(
              (status) => status.code == "switch_2",
              orElse: () => StatusModel(code: "switch_2", value: false));
          deviceStatus.firstSwitch = switch1Status.value as bool;
          deviceStatus.secondSwitch = switch2Status.value as bool;

          add(TwoTouchUpdated());
        }
      });
    } catch (_) {
    }
  }

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

  _twoTouchUpdated(TwoTouchUpdated event, Emitter<TwoTouchState> emit) {
    emit(LoadingInitialState());
    emit(UpdateState(twoTouchModel: deviceStatus));
  }

  void _changeFirstSwitch(
      ChangeFirstSwitchStatusEvent event, Emitter<TwoTouchState> emit) async {
    emit(LoadingNewSate(twoTouchModel: deviceStatus));
    try {
      deviceStatus.firstSwitch = !event.value;
      emit(UpdateState(twoTouchModel: deviceStatus));
      if (_timer != null) {
        _timer!.cancel();
      }

      _timer = Timer(const Duration(milliseconds: 100), () async {
        final response = await DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: twoTouchId, code: 'switch_1', value: !event.value),
            twoTouchId);

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

  void _changeSecondSwitch(
      ChangeSecondSwitchStatusEvent event, Emitter<TwoTouchState> emit) async {
    emit(LoadingNewSate(twoTouchModel: deviceStatus));
    try {
      deviceStatus.secondSwitch = !event.value;
      emit(UpdateState(twoTouchModel: deviceStatus));
      if (_timer != null) {
        _timer!.cancel();
      }
      _timer = Timer(const Duration(milliseconds: 100), () async {
        final response = await DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: twoTouchId, code: 'switch_2', value: !event.value),
            twoTouchId);

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

  void _allOff(AllOffEvent event, Emitter<TwoTouchState> emit) async {
    emit(LoadingNewSate(twoTouchModel: deviceStatus));

    try {
      deviceStatus.firstSwitch = false;
      deviceStatus.secondSwitch = false;
      emit(UpdateState(twoTouchModel: deviceStatus));

      final response = await Future.wait([
        DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: twoTouchId,
                code: 'switch_1',
                value: deviceStatus.firstSwitch),
            twoTouchId),
        DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: twoTouchId,
                code: 'switch_2',
                value: deviceStatus.secondSwitch),
            twoTouchId),
      ]);

      if (response.every((element) => !element['success'])) {
        await Future.delayed(const Duration(milliseconds: 500));
        add(const InitialEvent());
      }
    } catch (_) {
      await Future.delayed(const Duration(milliseconds: 500));
      add(const InitialEvent());
    }
  }

  void _allOn(AllOnEvent event, Emitter<TwoTouchState> emit) async {
    emit(LoadingNewSate(twoTouchModel: deviceStatus));
    try {
      deviceStatus.firstSwitch = true;
      deviceStatus.secondSwitch = true;
      emit(UpdateState(twoTouchModel: deviceStatus));
      final response = await Future.wait([
        DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: twoTouchId,
                code: 'switch_1',
                value: deviceStatus.firstSwitch),
            twoTouchId),
        DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: twoTouchId,
                code: 'switch_2',
                value: deviceStatus.secondSwitch),
            twoTouchId),
      ]);
      if (response.every((element) => !element['success'])) {
        await Future.delayed(const Duration(milliseconds: 500));
        add(const InitialEvent());
      }
    } catch (_) {
      await Future.delayed(const Duration(milliseconds: 500));
      add(const InitialEvent());
    }
  }

  void _groupAllOn(GroupAllOnEvent event, Emitter<TwoTouchState> emit) async {
    emit(LoadingNewSate(twoTouchModel: deviceStatus));
    try {
      for (int i = 0; i < groupTwoTouchList.length; i++) {
        groupTwoTouchList[i].firstSwitch = true;
        groupTwoTouchList[i].secondSwitch = true;
      }
      emit(
          UpdateGroupState(twoTouchList: groupTwoTouchList, allSwitches: true));
      List<String> allDeviceIds =
          groupTwoTouchList.map((device) => device.deviceId).toList();

      final response1 = await DevicesAPI.deviceBatchController(
        code: 'switch_1',
        devicesUuid: allDeviceIds,
        value: true,
      );

      final response2 = await DevicesAPI.deviceBatchController(
        code: 'switch_2',
        devicesUuid: allDeviceIds,
        value: true,
      );

      if (response1['failedResults'].toString() != '[]' ||
          response2['failedResults'].toString() != '[]') {
        await Future.delayed(const Duration(milliseconds: 500));
        add(InitialWizardEvent());
      }
    } catch (_) {
      await Future.delayed(const Duration(milliseconds: 500));
      add(InitialWizardEvent());
    }
  }

  void _groupAllOff(GroupAllOffEvent event, Emitter<TwoTouchState> emit) async {
    emit(LoadingNewSate(twoTouchModel: deviceStatus));
    try {
      for (int i = 0; i < groupTwoTouchList.length; i++) {
        groupTwoTouchList[i].firstSwitch = false;
        groupTwoTouchList[i].secondSwitch = false;
      }

      emit(UpdateGroupState(
          twoTouchList: groupTwoTouchList, allSwitches: false));

      List<String> allDeviceIds =
          groupTwoTouchList.map((device) => device.deviceId).toList();

      final response1 = await DevicesAPI.deviceBatchController(
        code: 'switch_1',
        devicesUuid: allDeviceIds,
        value: false,
      );

      final response2 = await DevicesAPI.deviceBatchController(
        code: 'switch_2',
        devicesUuid: allDeviceIds,
        value: false,
      );

      if (response1['failedResults'].toString() != '[]' ||
          response2['failedResults'].toString() != '[]') {
        await Future.delayed(const Duration(milliseconds: 500));
        add(InitialWizardEvent());
      }
    } catch (_) {
      await Future.delayed(const Duration(milliseconds: 500));
      add(InitialWizardEvent());
    }
  }

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

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

      if (response['success'] ?? false) {
        if (event.deviceCode == 'countdown_1') {
          deviceStatus.firstCountDown = seconds;
        } else if (event.deviceCode == 'countdown_2') {
          deviceStatus.secondCountDown = 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<TwoTouchState> emit) async {
    emit(LoadingInitialState());
    try {
      add(GetScheduleEvent());
      var response = await DevicesAPI.getDeviceStatus(twoTouchId);
      List<StatusModel> statusModelList = [];
      for (var status in response['status']) {
        statusModelList.add(StatusModel.fromJson(status));
      }
      deviceStatus = TwoTouchModel.fromJson(statusModelList);

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

  void _onClose(OnClose event, Emitter<TwoTouchState> 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<TwoTouchState> 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> toggleDaySelection(
    ToggleDaySelectionEvent event,
    Emitter<TwoTouchState> emit,
  ) async {
    emit(LoadingInitialState());
    if (selectedDays.contains(event.key)) {
      selectedDays.remove(event.key);
    } else {
      selectedDays.add(event.key);
    }
    emit(ChangeTimeState());
    add(const ChangeSlidingSegment(value: 1));
  }

  Future<void> saveSchedule(
    TwoTouchSave event,
    Emitter<TwoTouchState> emit,
  ) async {
    try {
      if (selectedDays.isNotEmpty) {
        emit(LoadingInitialState());
        await DevicesAPI.postSchedule(
            category: switchCode,
            deviceId: twoTouchId,
            time: getTimeStampWithoutSeconds(selectedTime).toString(),
            code: switchCode,
            value: toggleSchedule,
            days: selectedDays);
        CustomSnackBar.displaySnackBar('Save Successfully');
        add(GetScheduleEvent());
        emit(TwoTouchSaveSchedule());
        add(const ToggleCreateScheduleEvent(index: 1));
        // toggleCreateSchedule();
      } else {
        CustomSnackBar.displaySnackBar('Please select days');
      }
    } catch (e) {
      emit(FailedState(error: e.toString()));
    }
  }

  Future<void> getSchedule(
    GetScheduleEvent event,
    Emitter<TwoTouchState> emit,
  ) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.getSchedule(
        category: switchCode,
        deviceId: twoTouchId,
      );
      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 toggleRepeat(
      ToggleScheduleEvent event, Emitter<TwoTouchState> emit) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.changeSchedule(
          scheduleId: event.id, deviceUuid: twoTouchId, 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<TwoTouchState> emit) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.deleteSchedule(
        scheduleId: event.id,
        deviceUuid: twoTouchId,
      );
      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 _fetchTwoTouchWizardStatus(
      InitialWizardEvent event, Emitter<TwoTouchState> emit) async {
    emit(LoadingInitialState());
    try {
      devicesList = [];
      groupTwoTouchList = [];
      allSwitchesOn = true;
      devicesList = await DevicesAPI.getDeviceByGroupName(
          HomeCubit.getInstance().selectedSpace?.id ?? '', '2GT');

      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 = TwoTouchModel.fromJson(statusModelList);

        groupTwoTouchList.add(GroupTwoTouchModel(
          deviceId: devicesList[i].uuid ?? '',
          deviceName: devicesList[i].name ?? '',
          firstSwitch: deviceStatus.firstSwitch,
          secondSwitch: deviceStatus.secondSwitch,
        ));
      }

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

  void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event,
      Emitter<TwoTouchState> emit) async {
    emit(LoadingNewSate(twoTouchModel: deviceStatus));
    try {
      bool allSwitchesValue = true;
      groupTwoTouchList.forEach((element) {
        if (element.deviceId == event.deviceId) {
          element.firstSwitch = !event.value;
        }
        if (!element.firstSwitch || !element.secondSwitch) {
          allSwitchesValue = false;
        }
      });

      emit(UpdateGroupState(
          twoTouchList: groupTwoTouchList, allSwitches: allSwitchesValue));
      final response = await DevicesAPI.deviceBatchController(
        code: 'switch_1',
        devicesUuid: [event.deviceId],
        value: !event.value,
      );

      if (response['failedResults'].toString() != '[]') {
        add(InitialWizardEvent());
      }
    } catch (_) {
      add(InitialWizardEvent());
    }
  }

  void _changeSecondWizardSwitch(ChangeSecondWizardSwitchStatusEvent event,
      Emitter<TwoTouchState> emit) async {
    emit(LoadingNewSate(twoTouchModel: deviceStatus));
    try {
      bool allSwitchesValue = true;
      groupTwoTouchList.forEach((element) {
        if (element.deviceId == event.deviceId) {
          element.secondSwitch = !event.value;
        }
        if (!element.firstSwitch || !element.secondSwitch) {
          allSwitchesValue = false;
        }
      });

      emit(UpdateGroupState(
          twoTouchList: groupTwoTouchList, allSwitches: allSwitchesValue));

      final response = await DevicesAPI.deviceBatchController(
        code: 'switch_2',
        devicesUuid: [event.deviceId],
        value: !event.value,
      );

      if (response['failedResults'].toString() != '[]') {
        add(InitialWizardEvent());
      }
    } catch (_) {
      add(InitialWizardEvent());
    }
  }

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

  Future<void> _changeStatus(
      ChangeStatusEvent event, Emitter<TwoTouchState> 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',
        },
        "relay_status_2": {
          'Power On': 'power_on',
          'Power Off': 'power_off',
          'Restart Memory': 'last',
        },
      };

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