import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.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/water_heater_bloc/water_heater_event.dart';
import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_state.dart';
import 'package:syncrow_app/features/devices/model/GroupWHModel.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/schedule_model.dart';
import 'package:syncrow_app/features/devices/model/status_model.dart';
import 'package:syncrow_app/features/devices/model/water_heater.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/color_manager.dart';

class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
  final String whId;
  final String switchCode;
  WHModel deviceStatus = WHModel(firstSwitch: false, firstCountDown: 0);
  List<WHModel> deviceStatusList = [];
  List<DeviceModel> devicesList = [];
  bool allAcsPage = false;
  bool allAcsOn = true;
  bool allTempSame = true;
  int globalTemp = 25;
  Timer? _timer;

  bool toggleSchedule = true;
  List<String> selectedDays = [];
  bool createSchedule = false;
  bool createCirculate = false;
  List<ScheduleModel> listSchedule = [];
  DateTime? selectedTime = DateTime.now();

  WaterHeaterBloc({required this.whId, required this.switchCode})
      : super(WHInitialState()) {
    on<WaterHeaterInitial>(_fetchWaterHeaterStatus);
    on<WaterHeaterSwitch>(_changeFirstSwitch);
    on<SetCounterValue>(_setCounterValue);
    on<GetCounterEvent>(_getCounterValue);
    on<ToggleDaySelectionEvent>(toggleDaySelection);
    on<ScheduleSave>(saveSchedule);
    on<GetScheduleEvent>(getSchedule);
    on<ToggleScheduleEvent>(toggleChange);
    on<DeleteScheduleEvent>(deleteSchedule);
    on<TickTimer>(_onTickTimer);
    on<OnClose>(_onClose);
    on<SelectTimeEvent>(showTime);

    on<ToggleSelectedEvent>(toggleSelectedIndex);
    on<ToggleCreateScheduleEvent>(toggleCreateSchedule);
    on<InitialWizardEvent>(_fetchWHWizardStatus);
    on<ChangeFirstWizardSwitchStatusEvent>(_changeFirstWizardSwitch);

    on<GroupAllOnEvent>(_groupAllOn);
    on<GroupAllOffEvent>(_groupAllOff);
    on<ToggleCreateCirculate>(_toggleCreateCirculate);
    on<WaterHeaterUpdated>(_waterHeaterUpdated);
  }

  void _fetchWaterHeaterStatus(
      WaterHeaterInitial event, Emitter<WaterHeaterState> emit) async {
    emit(WHLoadingState());
    try {
      var response = await DevicesAPI.getDeviceStatus(whId);
      List<StatusModel> statusModelList = [];
      for (var status in response['status']) {
        statusModelList.add(StatusModel.fromJson(status));
      }
      deviceStatus = WHModel.fromJson(
        statusModelList,
      );
      emit(UpdateState(whModel: deviceStatus));
      _listenToChanges();
    } catch (e) {
      emit(WHFailedState(errorMessage: e.toString()));
      return;
    }
  }

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

      _streamSubscription = stream.listen((DatabaseEvent event) async {
        if (_timer != null) {
          await Future.delayed(const Duration(seconds: 2));
        }
        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 = WHModel.fromJson(statusList);
        if (!isClosed) {
          add(WaterHeaterUpdated());
        }
      });
    } catch (_) {}
  }

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

  _waterHeaterUpdated(
      WaterHeaterUpdated event, Emitter<WaterHeaterState> emit) async {
    emit(WHLoadingState());
    emit(UpdateState(whModel: deviceStatus));
  }

  void _changeFirstSwitch(
      WaterHeaterSwitch event, Emitter<WaterHeaterState> emit) async {
    emit(LoadingNewSate(whModel: deviceStatus));
    try {
      deviceStatus.firstSwitch = !event.whSwitch;
      emit(UpdateState(whModel: deviceStatus));
      if (_timer != null) {
        _timer!.cancel();
      }
      _timer = Timer(const Duration(milliseconds: 500), () async {
        final response = await DevicesAPI.controlDevice(
            DeviceControlModel(
                deviceId: whId,
                code: 'switch_1',
                value: deviceStatus.firstSwitch),
            whId);

        if (!response['success']) {
          // add(InitialEvent(groupScreen: oneGangGroup));
        }
      });
    } catch (_) {
      emit(WHFailedState(errorMessage: _.toString()));
    }
  }

  //=====================---------- timer ----------------------------------------

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

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

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

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

  void _onClose(OnClose event, Emitter<WaterHeaterState> 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<WaterHeaterState> emit) {
    if (event.remainingTime > 0) {
      emit(TimerRunInProgress(event.remainingTime));
    } else {
      _timer?.cancel();
      emit(TimerRunComplete());
    }
  }

  //=====================---------- Schedule ----------------------------------------

  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<WaterHeaterState> emit,
  ) async {
    try {
      if (selectedDays.isNotEmpty) {
        emit(WHLoadingState());
        await DevicesAPI.postSchedule(
            category: switchCode,
            deviceId: whId,
            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(WHFailedState(errorMessage: e.toString()));
    }
  }

  Future<void> getSchedule(
    GetScheduleEvent event,
    Emitter<WaterHeaterState> emit,
  ) async {
    try {
      emit(WHLoadingState());
      final response = await DevicesAPI.getSchedule(
        category: switchCode,
        deviceId: whId,
      );
      List<dynamic> jsonData = response;
      listSchedule =
          jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
      emit(WHInitialState());
    } on DioException catch (e) {
      final errorData = e.response!.data;
      String errorMessage = errorData['message'];
      emit(WHFailedState(errorMessage: 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<WaterHeaterState> emit) async {
    try {
      emit(WHLoadingState());
      final response = await DevicesAPI.changeSchedule(
          scheduleId: event.id, deviceUuid: whId, enable: event.toggle);
      if (response == true) {
        add(GetScheduleEvent());
        toggleSchedule = event.toggle;
        return toggleSchedule;
      }
      emit(IsToggleState(onOff: toggleSchedule));
    } on DioException catch (e) {
      final errorData = e.response!.data;
      String errorMessage = errorData['message'];
      emit(WHFailedState(errorMessage: errorMessage.toString()));
    }
  }

  Future deleteSchedule(
      DeleteScheduleEvent event, Emitter<WaterHeaterState> emit) async {
    try {
      emit(WHLoadingState());
      final response = await DevicesAPI.deleteSchedule(
        scheduleId: event.id,
        deviceUuid: whId,
      );
      if (response == true) {
        add(GetScheduleEvent());
        return toggleSchedule;
      }
      emit(IsToggleState(onOff: toggleSchedule));
    } on DioException catch (e) {
      final errorData = e.response!.data;
      String errorMessage = errorData['message'];
      emit(WHFailedState(errorMessage: errorMessage.toString()));
    }
  }

  void _toggleCreateCirculate(
      ToggleCreateCirculate event, Emitter<WaterHeaterState> emit) {
    emit(WHLoadingState());
    createCirculate = !createCirculate;
    selectedDays.clear();
    selectedTime = DateTime.now();
    emit(UpdateCreateScheduleState(createCirculate));
  }

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

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

  Future<void> toggleDaySelection(
    ToggleDaySelectionEvent event,
    Emitter<WaterHeaterState> emit,
  ) async {
    emit(WHLoadingState());
    if (selectedDays.contains(event.key)) {
      selectedDays.remove(event.key);
    } else {
      selectedDays.add(event.key);
    }
    emit(ChangeTimeState());
  }

  int selectedTabIndex = 0;

  showTime(SelectTimeEvent event, Emitter<WaterHeaterState> emit) async {
    await showTimePicker(
      context: event.context,
      initialTime: TimeOfDay.now(),
      builder: (context, child) {
        return Theme(
          data: ThemeData.light().copyWith(
            colorScheme: const ColorScheme.light(
              primary: ColorsManager.primaryColor,
              onSurface: Colors.black,
            ),
            buttonTheme: const ButtonThemeData(
              colorScheme: ColorScheme.light(
                primary: Colors.green,
              ),
            ),
          ),
          child: child!,
        );
      },
    );
  }

  List<GroupWHModel> groupWaterHeaterList = [];
  bool allSwitchesOn = true;

  void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event,
      Emitter<WaterHeaterState> emit) async {
    emit(LoadingNewSate(whModel: deviceStatus));
    try {
      bool allSwitchesValue = true;
      groupWaterHeaterList.forEach((element) {
        if (element.deviceId == event.deviceId) {
          element.firstSwitch = !event.value;
        }
        if (!element.firstSwitch) {
          allSwitchesValue = false;
        }
      });
      emit(UpdateGroupState(
          twoGangList: groupWaterHeaterList, 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 _fetchWHWizardStatus(
      InitialWizardEvent event, Emitter<WaterHeaterState> emit) async {
    emit(WHLoadingState());
    try {
      devicesList = [];
      groupWaterHeaterList = [];
      allSwitchesOn = true;
      devicesList = await DevicesAPI.getDeviceByGroupName(
          HomeCubit.getInstance().selectedSpace?.id ?? '', 'WH');

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

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

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

  void _groupAllOn(
      GroupAllOnEvent event, Emitter<WaterHeaterState> emit) async {
    emit(LoadingNewSate(whModel: deviceStatus));
    try {
      for (int i = 0; i < groupWaterHeaterList.length; i++) {
        groupWaterHeaterList[i].firstSwitch = true;
      }

      emit(UpdateGroupState(
          twoGangList: groupWaterHeaterList, allSwitches: true));

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

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

      if (response['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<WaterHeaterState> emit) async {
    emit(LoadingNewSate(whModel: deviceStatus));
    try {
      for (int i = 0; i < groupWaterHeaterList.length; i++) {
        groupWaterHeaterList[i].firstSwitch = false;
      }
      emit(UpdateGroupState(
          twoGangList: groupWaterHeaterList, allSwitches: false));

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

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

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