import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:syncrow_app/features/devices/bloc/power_clamp_bloc/power_clamp_event.dart';
import 'package:syncrow_app/features/devices/bloc/power_clamp_bloc/power_clamp_state.dart';
import 'package:syncrow_app/features/devices/model/device_report_model.dart';
import 'package:syncrow_app/features/devices/model/power_clamp_model.dart';
import 'package:syncrow_app/features/devices/view/widgets/power_clamp/power_chart.dart';
import 'package:syncrow_app/services/api/devices_api.dart';

class PowerClampBloc extends Bloc<PowerClampEvent, PowerClampState> {
  final String PCId;
  PowerClampBloc({
    required this.PCId,
  }) : super(const PowerClampState()) {
    on<PowerClampInitial>(_fetchPowerClampInfo);
    // on<ReportLogsInitial>(fetchLogsForLastMonth);
    // on<FetchEnergyData>(_mapReportToEnergyData);
    on<SelectDateEvent>(checkDayMonthYearSelected);
    on<FilterRecordsByDateEvent>(_filterRecordsByDate);
  }
  DateTime? dateTime = DateTime.now();

  String formattedDate = DateFormat('dd/MM/yyyy').format(DateTime.now());
  bool lowBattery = false;
  bool closingReminder = false;
  bool doorAlarm = false;

  PowerClampModel deviceStatus = PowerClampModel(
    productType: '',
    productUuid: '',
    status: PowerStatus(
      phaseA: Phase(
        dataPoints: [
          DataPoint(
              code: '', customName: '', dpId: 0, time: 0, type: '', value: 0),
        ],
      ),
      phaseB: Phase(
        dataPoints: [
          DataPoint(
              code: '', customName: '', dpId: 0, time: 0, type: '', value: 0),
        ],
      ),
      phaseC: Phase(
        dataPoints: [
          DataPoint(
              code: '', customName: '', dpId: 0, time: 0, type: '', value: 0),
        ],
      ),
      general: Phase(
        dataPoints: [
          DataPoint(
              code: '', customName: '', dpId: 0, time: 0, type: '', value: 0),
        ],
      ),
    ),
  );

  void _fetchPowerClampInfo(
      PowerClampInitial event, Emitter<PowerClampState> emit) async {
    emit(PowerClampLoadingState());
    try {
      var response = await DevicesAPI.getPowerClampStatus(PCId);
      PowerClampModel deviceStatus = PowerClampModel.fromJson(response);
      emit(UpdateState(powerClampModel: deviceStatus));
    } catch (e) {
      emit(PowerClampFailedState(errorMessage: e.toString()));
      return;
    }
  }

  DeviceReport recordGroups =
      DeviceReport(startTime: '0', endTime: '0', data: []);

  EventDevice recordGroupsDateTime =
      EventDevice(code: '', eventTime: DateTime.now(), value: '');

  List<EventDevice> record = [
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:15:43'),
        value: '2286'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:15:35'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:15:29'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:15:25'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:15:21'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:15:17'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:15:07'),
        value: '2286'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:14:47'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:14:40'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:14:23'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2024-10-23 11:14:13'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:15:43'),
        value: '2286'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:15:35'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:15:29'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:15:25'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:15:21'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:15:17'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:15:07'),
        value: '2286'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:14:47'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:14:40'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:14:23'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-10-23 11:14:13'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:15:43'),
        value: '2286'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:15:35'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:15:29'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:15:25'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:15:21'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:15:17'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:15:07'),
        value: '2286'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:14:47'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:14:40'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:14:23'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-23 11:14:13'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-11 11:15:43'),
        value: '2286'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-11 11:15:35'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-12 11:15:29'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-13 11:15:25'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-14 11:15:21'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-15 11:15:17'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-16 11:15:07'),
        value: '2286'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-17 11:14:47'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-18 11:14:40'),
        value: '2284'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-19 11:14:23'),
        value: '2285'),
    EventDevice(
        code: 'VoltageA',
        eventTime: DateTime.parse('2023-02-20 11:14:13'),
        value: '2284'),
  ];
  List<EventDevice> filteredRecords = [];

  int currentIndex = 0;
  final List<String> views = ['Day', 'Month', 'Year'];

  Widget dateSwitcher() {
    void switchView(int direction) {
      currentIndex = (currentIndex + direction + views.length) % views.length;
    }

    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        return Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: const Icon(Icons.arrow_left),
              onPressed: () {
                setState(() {
                  switchView(-1);
                });
              },
            ),
            Text(
              views[currentIndex],
              style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
            ),
            IconButton(
              icon: const Icon(Icons.arrow_right),
              onPressed: () {
                setState(() {
                  switchView(1);
                });
              },
            ),
          ],
        );
      },
    );
  }

  void checkDayMonthYearSelected(
      SelectDateEvent event, Emitter<PowerClampState> emit) async {
    emit(PowerClampLoadingState());

    if (currentIndex == 0) {
      await dayMonthYearPicker(context: event.context).then(
        (newDate) {
          if (newDate != null) {
            dateTime = newDate;
            // formattedDate = DateFormat('yyyy/MM/dd').format(dateTime!);
            formattedDate = DateFormat('dd/MM/yyyy').format(dateTime!);
            add(FilterRecordsByDateEvent(
              selectedDate: dateTime!,
              viewType: views[currentIndex],
            ));
          }
        },
      );
    } else if (currentIndex == 1) {
      await selectMonthAndYear(event.context).then(
        (newDate) {
          if (newDate != null) {
            dateTime = newDate;
            formattedDate = DateFormat('yyyy/MM').format(dateTime!);
            add(FilterRecordsByDateEvent(
              selectedDate: dateTime!,
              viewType: views[currentIndex],
            ));
          }
        },
      );
    } else if (currentIndex == 2) {
      await selectYear(event.context).then(
        (newDate) {
          if (newDate != null) {
            dateTime = newDate;
            formattedDate = DateFormat('yyyy').format(dateTime!);

            add(FilterRecordsByDateEvent(
              selectedDate: dateTime!,
              viewType: views[currentIndex],
            ));
          }
        },
      );
    }
    emit(DateSelectedState());
  }

  Future<DateTime?> selectMonthAndYear(BuildContext context) async {
    int selectedYear = DateTime.now().year;
    int selectedMonth = DateTime.now().month;

    FixedExtentScrollController yearController =
        FixedExtentScrollController(initialItem: selectedYear - 1905);
    FixedExtentScrollController monthController =
        FixedExtentScrollController(initialItem: selectedMonth - 1);

    return await showModalBottomSheet<DateTime>(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          height: MediaQuery.of(context).size.height * 0.4,
          child: Column(
            children: [
              const Padding(
                padding: EdgeInsets.all(16.0),
                child: Text(
                  'Select Month and Year',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
              ),
              const Divider(),
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Spacer(),
                    Expanded(
                      child: ListWheelScrollView.useDelegate(
                        controller: yearController,
                        overAndUnderCenterOpacity: 0.2,
                        itemExtent: 50,
                        onSelectedItemChanged: (index) {
                          selectedYear = 1905 + index;
                        },
                        childDelegate: ListWheelChildBuilderDelegate(
                          builder: (context, index) {
                            return Center(
                              child: Text(
                                (1905 + index).toString(),
                                style: const TextStyle(fontSize: 18),
                              ),
                            );
                          },
                          childCount: 200,
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 2,
                      child: ListWheelScrollView.useDelegate(
                        controller: monthController,
                        overAndUnderCenterOpacity: 0.2,
                        itemExtent: 50,
                        onSelectedItemChanged: (index) {
                          selectedMonth = index + 1;
                        },
                        childDelegate: ListWheelChildBuilderDelegate(
                          builder: (context, index) {
                            return Center(
                              child: Text(
                                DateFormat.MMMM()
                                    .format(DateTime(0, index + 1)),
                                style: const TextStyle(fontSize: 18),
                              ),
                            );
                          },
                          childCount: 12,
                        ),
                      ),
                    ),
                    const Spacer(),
                  ],
                ),
              ),
              const Divider(),
              Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    TextButton(
                      child: const Text('Cancel'),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                    TextButton(
                      child: const Text('OK'),
                      onPressed: () {
                        final selectedDateTime =
                            DateTime(selectedYear, selectedMonth);
                        Navigator.of(context).pop(selectedDateTime);
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<DateTime?> selectYear(BuildContext context) async {
    int selectedYear = DateTime.now().year;
    FixedExtentScrollController yearController =
        FixedExtentScrollController(initialItem: selectedYear - 1905);

    return await showModalBottomSheet<DateTime>(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          height: MediaQuery.of(context).size.height * 0.4,
          child: Column(
            children: [
              const Padding(
                padding: EdgeInsets.all(16.0),
                child: Text(
                  'Select Year',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
              ),
              const Divider(),
              Expanded(
                child: ListWheelScrollView.useDelegate(
                  controller: yearController,
                  overAndUnderCenterOpacity: 0.2,
                  itemExtent: 50,
                  onSelectedItemChanged: (index) {
                    selectedYear = 1905 + index;
                  },
                  childDelegate: ListWheelChildBuilderDelegate(
                    builder: (context, index) {
                      return Center(
                        child: Text(
                          (1905 + index).toString(),
                          style: const TextStyle(fontSize: 18),
                        ),
                      );
                    },
                    childCount: 200,
                  ),
                ),
              ),
              const Divider(),
              Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    TextButton(
                      child: const Text('Cancel'),
                      onPressed: () {
                        Navigator.of(context)
                            .pop(); // Pops without value, returning null
                      },
                    ),
                    TextButton(
                      child: const Text('OK'),
                      onPressed: () {
                        final selectedDateTime = DateTime(selectedYear);
                        Navigator.of(context).pop(
                            selectedDateTime); // Pops with the selected date
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<DateTime?> dayMonthYearPicker({
    required BuildContext context,
  }) async {
    DateTime selectedDate = DateTime.now();

    return await showModalBottomSheet<DateTime>(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          height: MediaQuery.of(context).size.height * 0.4,
          child: Column(
            children: [
              Expanded(
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  initialDateTime: DateTime.now(),
                  minimumYear: 1900,
                  maximumYear: DateTime.now().year,
                  onDateTimeChanged: (DateTime newDateTime) {
                    selectedDate = newDateTime;
                  },
                ),
              ),
              const Divider(),
              Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    TextButton(
                      child: const Text('Cancel'),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                    TextButton(
                      child: const Text('OK'),
                      onPressed: () {
                        Navigator.of(context).pop(selectedDate);
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  List<EnergyData> energyDataList = [];
  void _filterRecordsByDate(
      FilterRecordsByDateEvent event, Emitter<PowerClampState> emit) {
    emit(PowerClampLoadingState());
    if (event.viewType == 'Year') {
      filteredRecords = record
          .where((record) => record.eventTime!.year == event.selectedDate.year)
          .toList();
    } else if (event.viewType == 'Month') {
      formattedDate =
          "${getMonthShortName(event.selectedDate.month)} ${event.selectedDate.year.toString()}";
      filteredRecords = record
          .where((record) =>
              record.eventTime!.year == event.selectedDate.year &&
              record.eventTime!.month == event.selectedDate.month)
          .toList();
    } else if (event.viewType == 'Day') {
      filteredRecords = record
          .where((record) =>
              record.eventTime!.year == event.selectedDate.year &&
              record.eventTime!.month == event.selectedDate.month &&
              record.eventTime!.day == event.selectedDate.day)
          .toList();
    }

    energyDataList = filteredRecords.map((eventDevice) {
      return EnergyData(
        event.viewType == 'Year'
            ? getMonthShortName(
                int.tryParse(DateFormat('MM').format(eventDevice.eventTime!))!)
            : event.viewType == 'Month'
                ? DateFormat('dd/MM').format(eventDevice.eventTime!)
                : DateFormat('HH:mm:ss').format(eventDevice.eventTime!),
        double.parse(eventDevice.value!),
      );
    }).toList();
    selectDateRange();
    Future.delayed(const Duration(milliseconds: 500));
    emit(FilterRecordsState(filteredRecords: energyDataList));
  }

  String getMonthShortName(int month) {
    final date = DateTime(0, month);
    return DateFormat.MMM().format(date);
  }

  String endChartDate = '';

  void selectDateRange() async {
    DateTime startDate = dateTime!;
    DateTime endDate = DateTime(startDate.year, startDate.month + 1, 1)
        .subtract(Duration(days: 1));
    String formattedEndDate = DateFormat('dd/MM/yyyy').format(endDate);
    endChartDate = ' - $formattedEndDate';
  }
}



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

//     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: true));
//       });

//       deviceStatus = PowerClampModel.fromJson(statusList);
//       if (!isClosed) {
//         add(
//           PowerClampSwitch(switchD: deviceStatus.doorContactState),
//         );
//       }
//     });
//   } catch (_) {}
// }

// New Function: Convert the device report data into EnergyData and emit it.
// void _mapReportToEnergyData(
//     FetchEnergyData event, Emitter<PowerClampState> emit) {
//   try {
//     List<EnergyData> energyDataList = recordGroups.data
//             ?.map((event) {
//               if (event.code == "VoltageA" && event.eventTime != null) {
//                 // Convert eventTime to readable format
//                 DateTime eventDateTime =
//                     DateTime.fromMillisecondsSinceEpoch(event.eventTime!);
//                 String formattedTime =
//                     "${eventDateTime.hour}:${eventDateTime.minute.toString().padLeft(2, '0')} ${eventDateTime.hour >= 12 ? 'PM' : 'AM'}";
//                 double value = double.tryParse(event.value ?? "0") ?? 0;
//                 return EnergyData(
//                     formattedTime, value / 1000); // Assume kWh format
//               }
//               return null;
//             })
//             .where((data) => data != null)
//             .cast<EnergyData>()
//             .toList() ??
//         [];

//     emit(EnergyDataState(energyData: energyDataList));
//   } catch (e) {
//     emit(PowerClampFailedState(errorMessage: e.toString()));
//   }
// }

 // Future<void> selectTimeOfLinePassword(
  //     SelectDateEvent event, Emitter<PowerClampState> emit) async {
  //   emit(ChangeTimeState());
  //   final DateTime? picked = await showDatePicker(
  //     initialDatePickerMode: DatePickerMode.year,
  //     context: event.context,
  //     initialDate: DateTime.now(),
  //     firstDate: DateTime(1905),
  //     lastDate: DateTime(2101),
  //   );
  //   if (picked != null) {
  //     final selectedDateTime = DateTime(
  //       picked.year,
  //       picked.month,
  //       picked.day,
  //       0,
  //       0,
  //     );
  //     final selectedTimestamp = DateTime(
  //           selectedDateTime.year,
  //           selectedDateTime.month,
  //           selectedDateTime.day,
  //           selectedDateTime.hour,
  //           selectedDateTime.minute,
  //         ).millisecondsSinceEpoch ~/
  //         1000;

  //     DateTime dateTime = selectedDateTime;
  //      formattedDate = DateFormat('yyyy/MM/dd').format(dateTime);
  //     emit(DateSelectedState());
  //   }
  // }

    // void _fetchStatus(
  //     PowerClampInitial event, Emitter<PowerClampState> emit) async {
  //   emit(PowerClampLoadingState());
  //   try {
  //     var response = await DevicesAPI.getDeviceStatus(PCId);
  //     List<StatusModel> statusModelList = [];
  //     for (var status in response['status']) {
  //       statusModelList.add(StatusModel.fromJson(status));
  //     }
  //     deviceStatus = PowerClampModel.fromJson(
  //       statusModelList,
  //     );
  //     emit(UpdateState(powerClampModel: deviceStatus));
  //     Future.delayed(const Duration(milliseconds: 500));
  //     // _listenToChanges();
  //   } catch (e) {
  //     emit(PowerClampFailedState(errorMessage: e.toString()));
  //     return;
  //   }
  // }


  // Future<void> fetchLogsForLastMonth(
  //     ReportLogsInitial event, Emitter<PowerClampState> emit) async {
  //   DateTime now = DateTime.now();
  //   DateTime lastMonth = DateTime(now.year, now.month - 1, now.day);

  //   int startTime = lastMonth.millisecondsSinceEpoch;
  //   int endTime = now.millisecondsSinceEpoch;

  //   try {
  //     emit(PowerClampLoadingState());
  //     var response = await DevicesAPI.getReportLogs(
  //       startTime: startTime.toString(),
  //       endTime: endTime.toString(),
  //       deviceUuid: PCId,
  //       code: event.code!,
  //     );
  //     recordGroups = response;
  //     record = recordGroups.data!.map((event) {
  //       return EventDevice(
  //         code: event.code,
  //         eventTime: event.eventTime != null
  //             ? DateTime.fromMillisecondsSinceEpoch(event.eventTime!)
  //             : null,
  //         value: event.value,
  //       );
  //     }).toList();
  //     for (var event in record) {
  //       print(
  //           'Code: ${event.code}, Event Time: ${DateFormat('yyyy-MM-dd hh:mm:ss a').format(event.eventTime!)}, Value: ${event.value}');
  //     }
  //     emit(UpdateState(powerClampModel: deviceStatus));
  //   } on DioException catch (e) {
  //     final errorData = e.response!.data;
  //     String errorMessage = errorData['message'];
  //   }
  // }
    // int transformTimestamp(int originalTime) {
  //   DateTime originalDateTime =
  //       DateTime.fromMillisecondsSinceEpoch(originalTime);
  //   DateTime transformedDateTime = originalDateTime.add(Duration(hours: 1));
  //   return transformedDateTime.millisecondsSinceEpoch;
  // }

  // void addDataToRecord(List<Map<String, dynamic>> rawData) {
  //   for (var dataPoint in rawData) {
  //     EventDevice event = EventDevice.fromJson(dataPoint);
  //     record.add(event);
  //   }
  // }