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_gang_bloc/two_gang_event.dart';
import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_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_gang_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_gang_model.dart';
import 'package:syncrow_app/services/api/devices_api.dart';
import 'package:syncrow_app/utils/helpers/snack_bar.dart';

class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
  final String twoGangId;
  final String switchCode;
  TwoGangModel deviceStatus = TwoGangModel(
    firstSwitch: false,
    secondSwitch: false,
    firstCountDown: 0,
    secondCountDown: 0,
  );
  Timer? _timer;

  bool twoGangGroup = false;
  List<DeviceModel> devicesList = [];
  List<GroupTwoGangModel> groupTwoGangList = [];
  bool allSwitchesOn = true;
  bool toggleSchedule = true;
  List<String> selectedDays = [];

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

  TwoGangBloc({required this.twoGangId, required this.switchCode})
      : super(InitialState()) {
    on<InitialEvent>(_fetchTwoGangStatus);
    on<TwoGangUpdated>(_twoGangUpdated);
    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<TwoGangSave>(saveSchedule);
    on<GetScheduleEvent>(getSchedule);
    on<ToggleScheduleEvent>(toggleRepeat);
    on<DeleteScheduleEvent>(deleteSchedule);
    on<ToggleSelectedEvent>(toggleSelectedIndex);
    on<ToggleCreateScheduleEvent>(toggleCreateSchedule);
    on<InitialWizardEvent>(_fetchTwoGangWizardStatus);
    on<ChangeFirstWizardSwitchStatusEvent>(_changeFirstWizardSwitch);
    on<ChangeSecondWizardSwitchStatusEvent>(_changeSecondWizardSwitch);
  }

  DateTime? selectedTime = DateTime.now();

  int selectedTabIndex = 0;

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

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

  void _fetchTwoGangStatus(
      InitialEvent event, Emitter<TwoGangState> emit) async {
    emit(LoadingInitialState());
    try {
      var response = await DevicesAPI.getDeviceStatus(twoGangId);
      List<StatusModel> statusModelList = [];
      for (var status in response['status']) {
        statusModelList.add(StatusModel.fromJson(status));
      }
      deviceStatus = TwoGangModel.fromJson(statusModelList);
      emit(UpdateState(twoGangModel: deviceStatus));
      _listenToChanges(twoGangId);
    } 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) {
        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']));
        });
        deviceStatus = TwoGangModel.fromJson(statusList);
        add(TwoGangUpdated());
      });
    } catch (_) {}
  }

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

  _twoGangUpdated(TwoGangUpdated event, Emitter<TwoGangState> emit) {
    emit(LoadingNewSate(twoGangModel: deviceStatus));

    emit(UpdateState(twoGangModel: deviceStatus));
  }

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

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

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

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

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

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

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

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

      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<TwoGangState> emit) async {
    emit(LoadingNewSate(twoGangModel: deviceStatus));
    try {
      deviceStatus.firstSwitch = true;
      deviceStatus.secondSwitch = true;
      emit(UpdateState(twoGangModel: deviceStatus));
      final response = await Future.wait([
        DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: twoGangId,
                code: 'switch_1',
                value: deviceStatus.firstSwitch),
            twoGangId),
        DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: twoGangId,
                code: 'switch_2',
                value: deviceStatus.secondSwitch),
            twoGangId),
      ]);
      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<TwoGangState> emit) async {
    emit(LoadingNewSate(twoGangModel: deviceStatus));
    try {
      for (int i = 0; i < groupTwoGangList.length; i++) {
        groupTwoGangList[i].firstSwitch = true;
        groupTwoGangList[i].secondSwitch = true;
      }
      emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true));
      List<String> allDeviceIds =
          groupTwoGangList.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<TwoGangState> emit) async {
    emit(LoadingNewSate(twoGangModel: deviceStatus));
    try {
      for (int i = 0; i < groupTwoGangList.length; i++) {
        groupTwoGangList[i].firstSwitch = false;
        groupTwoGangList[i].secondSwitch = false;
      }

      emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false));

      List<String> allDeviceIds =
          groupTwoGangList.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<TwoGangState> emit) async {
    emit(ChangeSlidingSegmentState(value: event.value));
  }

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

      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<TwoGangState> emit) async {
    emit(LoadingInitialState());
    try {
      add(GetScheduleEvent());
      var response = await DevicesAPI.getDeviceStatus(twoGangId);
      List<StatusModel> statusModelList = [];
      for (var status in response['status']) {
        statusModelList.add(StatusModel.fromJson(status));
      }
      deviceStatus = TwoGangModel.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<TwoGangState> 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<TwoGangState> 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<TwoGangState> 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(
    TwoGangSave event,
    Emitter<TwoGangState> emit,
  ) async {
    try {
      if (selectedDays.isNotEmpty) {
        emit(LoadingInitialState());
        await DevicesAPI.postSchedule(
            category: switchCode,
            deviceId: twoGangId,
            time: getTimeStampWithoutSeconds(selectedTime).toString(),
            code: switchCode,
            value: toggleSchedule,
            days: selectedDays);
        CustomSnackBar.displaySnackBar('Save Successfully');
        add(GetScheduleEvent());
        emit(TwoGangSaveSchedule());
        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<TwoGangState> emit,
  ) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.getSchedule(
        category: switchCode,
        deviceId: twoGangId,
      );
      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<TwoGangState> emit) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.changeSchedule(
          scheduleId: event.id, deviceUuid: twoGangId, 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<TwoGangState> emit) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.deleteSchedule(
        scheduleId: event.id,
        deviceUuid: twoGangId,
      );
      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 _fetchTwoGangWizardStatus(
      InitialWizardEvent event, Emitter<TwoGangState> emit) async {
    emit(LoadingInitialState());
    try {
      devicesList = [];
      groupTwoGangList = [];
      allSwitchesOn = true;
      devicesList = await DevicesAPI.getDeviceByGroupName(
          HomeCubit.getInstance().selectedSpace?.id ?? '', '2G');

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

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

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

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

      emit(UpdateGroupState(
          twoGangList: groupTwoGangList, allSwitches: allSwitchesValue));

      List<String> allDeviceIds =
          groupTwoGangList.map((device) => device.deviceId).toList();
      final response = await DevicesAPI.deviceBatchController(
        code: 'switch_1',
        devicesUuid: allDeviceIds,
        value: !event.value,
      );

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

  void _changeSecondWizardSwitch(ChangeSecondWizardSwitchStatusEvent event,
      Emitter<TwoGangState> emit) async {
    emit(LoadingNewSate(twoGangModel: deviceStatus));
    try {
      bool allSwitchesValue = true;
      groupTwoGangList.forEach((element) {
        if (element.deviceId == event.deviceId) {
          element.secondSwitch = !event.value;
        }
        if (!element.firstSwitch || !element.secondSwitch) {
          allSwitchesValue = false;
        }
      });
      List<String> allDeviceIds =
          groupTwoGangList.map((device) => device.deviceId).toList();

      emit(UpdateGroupState(
          twoGangList: groupTwoGangList, allSwitches: allSwitchesValue));

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

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