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/one_gang_bloc/one_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_one_gang_model.dart';
import 'package:syncrow_app/features/devices/model/one_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/services/api/devices_api.dart';
import 'package:syncrow_app/utils/helpers/snack_bar.dart';
import 'one_gang_event.dart';

class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
  final String oneGangId;
  final String switchCode;
  OneGangModel deviceStatus = OneGangModel(
    firstSwitch: false,
    firstCountDown: 0,
  );
  Timer? _timer;

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

  OneGangBloc({required this.oneGangId, required this.switchCode})
      : super(InitialState()) {
    on<InitialEvent>(_fetchOneGangStatus);
    on<OneGangUpdated>(_oneGangUpdated);
    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>(_fetchOneGangWizardStatus);
    on<ChangeFirstWizardSwitchStatusEvent>(_changeFirstWizardSwitch);
    on<GroupAllOnEvent>(_groupAllOn);
    on<GroupAllOffEvent>(_groupAllOff);
  }

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

  // Real-time db
  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 = OneGangModel.fromJson(statusList);
        add(OneGangUpdated());
      });
    } catch (_) {}
  }

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

  _oneGangUpdated(OneGangUpdated event, Emitter<OneGangState> emit) {
    emit(LoadingInitialState());
    emit(UpdateState(oneGangModel: deviceStatus));
  }

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

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

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

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

      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<OneGangState> emit) async {
    emit(LoadingInitialState());
    try {
      var response = await DevicesAPI.getDeviceStatus(oneGangId);
      List<StatusModel> statusModelList = [];
      for (var status in response['status']) {
        statusModelList.add(StatusModel.fromJson(status));
      }
      deviceStatus = OneGangModel.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<OneGangState> 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<OneGangState> 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<OneGangState> emit,
  ) async {
    try {
      if (selectedDays.isNotEmpty) {
        emit(LoadingInitialState());
        await DevicesAPI.postSchedule(
            category: switchCode,
            deviceId: oneGangId,
            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<OneGangState> emit,
  ) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.getSchedule(
        category: switchCode,
        deviceId: oneGangId,
      );
      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<OneGangState> emit) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.changeSchedule(
          scheduleId: event.id, deviceUuid: oneGangId, 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<OneGangState> emit) async {
    try {
      emit(LoadingInitialState());
      final response = await DevicesAPI.deleteSchedule(
        scheduleId: event.id,
        deviceUuid: oneGangId,
      );
      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<OneGangState> 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<OneGangState> 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));
  }

  int selectedTabIndex = 0;

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

  List<GroupOneGangModel> groupOneGangList = [];
  bool allSwitchesOn = true;

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

      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 = OneGangModel.fromJson(statusModelList);
        groupOneGangList.add(GroupOneGangModel(
          deviceId: devicesList[i].uuid ?? '',
          deviceName: devicesList[i].name ?? '',
          firstSwitch: deviceStatus.firstSwitch,
        ));
      }

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

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

      emit(UpdateGroupState(
          oneGangList: groupOneGangList, allSwitches: allSwitchesValue));

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

      if (response['failedResults'].toString() != '[]') {
        add(InitialEvent(groupScreen: oneGangGroup));
      }
    } catch (_) {
      add(InitialEvent(groupScreen: oneGangGroup));
    }
  }

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

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

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

      // First call for switch_1
      final response = 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
      );
      // Check if either response is unsuccessful, then reset to initial state
      if (response['failedResults'].toString() != '[]') {
        await Future.delayed(const Duration(milliseconds: 500));
        add(const InitialEvent(groupScreen: true));
      }
    } catch (_) {
      // 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<OneGangState> emit) async {
    emit(LoadingNewSate(oneGangModel: deviceStatus));
    try {
      // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off)
      for (int i = 0; i < groupOneGangList.length; i++) {
        groupOneGangList[i].firstSwitch = false;
      }

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

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

      // First call for switch_1
      final response = 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 (response['failedResults'].toString() != '[]') {
        await Future.delayed(const Duration(milliseconds: 500));
        add(const InitialEvent(groupScreen: true));
      }
    } catch (_) {
      // 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));
    }
  }
}
