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_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/power_clamp/bloc/smart_power_event.dart';
import 'package:syncrow_web/pages/device_managment/power_clamp/bloc/smart_power_state.dart';
import 'package:syncrow_web/pages/device_managment/power_clamp/models/device_event.dart';
import 'package:syncrow_web/pages/device_managment/power_clamp/models/power_clamp_batch_model.dart';
import 'package:syncrow_web/pages/device_managment/power_clamp/models/power_clamp_model.dart';
import 'package:syncrow_web/pages/device_managment/power_clamp/view/power_chart.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class SmartPowerBloc extends Bloc<SmartPowerEvent, SmartPowerState> {
  SmartPowerBloc({required this.deviceId}) : super(SmartPowerInitial()) {
    on<SmartPowerFetchDeviceEvent>(_onFetchDeviceStatus);
    on<SmartPowerArrowPressedEvent>(_onArrowPressed);
    on<SmartPowerFetchBatchEvent>(_onFetchBatchStatus);
    on<SmartPowerPageChangedEvent>(_onPageChanged);
    on<PowerBatchControlEvent>(_onBatchControl);
    on<FilterRecordsByDateEvent>(_filterRecordsByDate);
    on<SelectDateEvent>(checkDayMonthYearSelected);
    on<SmartPowerFactoryReset>(_onFactoryReset);
  }

  late PowerClampModel deviceStatus;
  late PowerClampBatchModel deviceBatchStatus;
  final String deviceId;
  Timer? _timer;
  List<Map<String, dynamic>> phaseData = [];
  int currentPage = 0;

  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'),
  ];

  FutureOr<void> _onFetchDeviceStatus(
      SmartPowerFetchDeviceEvent event, Emitter<SmartPowerState> emit) async {
    emit(SmartPowerLoading());
    try {
      var status =
          await DevicesManagementApi().getPowerClampInfo(event.deviceId);
      deviceStatus = PowerClampModel.fromJson(status as Map<String, Object?>? ??{});
      final phaseADataPoints = deviceStatus.status.phaseA.dataPoints;
      final phaseBDataPoints = deviceStatus.status.phaseB.dataPoints;
      final phaseCDataPoints = deviceStatus.status.phaseC.dataPoints;
      phaseData = [
        {
          'name': 'Phase A',
          'voltage': '${(phaseADataPoints.elementAtOrNull(0)?.value as num? ?? 0) / 10} V',
          'current': '${(phaseADataPoints.elementAtOrNull(1)?.value as num? ?? 0) / 10} A',
          'activePower': '${phaseADataPoints.elementAtOrNull(2)?.value??'N/A'} W',
          'powerFactor': '${phaseADataPoints.elementAtOrNull(3)?.value??'N/A'}',
        },
        {
          'name': 'Phase B',
          'voltage': '${(phaseBDataPoints .elementAtOrNull(0)?.value  as num? ?? 0) / 10} V',
          'current': '${(phaseBDataPoints .elementAtOrNull(1)?.value as num? ?? 0) / 10} A',
          'activePower': '${phaseBDataPoints.elementAtOrNull(2)?.value??'N/A'} W',
          'powerFactor': '${phaseBDataPoints.elementAtOrNull(3)?.value??'N/A'}',
        },
        {
          'name': 'Phase C',
          'voltage': '${(phaseCDataPoints.elementAtOrNull(0)?.value as num? ?? 0) / 10} V',
          'current': '${(phaseCDataPoints.elementAtOrNull(1)?.value as num? ?? 0) / 10} A',
          'activePower': '${phaseCDataPoints.elementAtOrNull(2)?.value ?? 'N/A'} W',
          'powerFactor': '${phaseCDataPoints.elementAtOrNull(3)?.value ?? 'N/A'}',
        },
      ];
      emit(GetDeviceStatus());
    } catch (e) {
      emit(SmartPowerError(e.toString()));
    }
  }

  FutureOr<void> _onArrowPressed(
      SmartPowerArrowPressedEvent event, Emitter<SmartPowerState> emit) {
    currentPage = (currentPage + event.direction + 4) % 4;
    emit(SmartPowerStatusLoaded(deviceStatus, currentPage));
    emit(GetDeviceStatus());
  }

  FutureOr<void> _onPageChanged(
      SmartPowerPageChangedEvent event, Emitter<SmartPowerState> emit) {
    currentPage = event.page;
    emit(SmartPowerStatusLoaded(deviceStatus, currentPage));
    emit(GetDeviceStatus());
  }

  Future<void> _onFactoryReset(
      SmartPowerFactoryReset event, Emitter<SmartPowerState> emit) async {
    emit(SmartPowerLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (response) {
        emit(SmartPowerInitial());
      } else {
        emit(SmartPowerError('Factory reset failed'));
      }
    } catch (e) {
      emit(SmartPowerError(e.toString()));
    }
  }

  Future<void> _onBatchControl(
      PowerBatchControlEvent event, Emitter<SmartPowerState> emit) async {
    final oldValue = deviceStatus.status;

    _updateLocalValue(event.code, event.value);
    // emit(WaterLeakBatchStatusLoadedState(deviceStatus!));

    await _runDebounce(
      deviceId: event.deviceIds,
      code: event.code,
      value: event.value,
      oldValue: oldValue,
      emit: emit,
      isBatch: true,
    );
  }

  Future<void> _onFetchBatchStatus(
      SmartPowerFetchBatchEvent event, Emitter<SmartPowerState> emit) async {
    emit(SmartPowerLoading());
    try {
      final response =
          await DevicesManagementApi().getPowerStatus(event.devicesIds);
      PowerClampBatchModel deviceStatus =
          PowerClampBatchModel.fromJson(response);

      emit(SmartPowerLoadBatchControll(deviceStatus));
    } catch (e) {
      debugPrint('=========error====$e');
      emit(SmartPowerError(e.toString()));
    }
  }

  Future<void> _runDebounce({
    required dynamic deviceId,
    required String code,
    required dynamic value,
    required dynamic oldValue,
    required Emitter<SmartPowerState> emit,
    required bool isBatch,
  }) async {
    late String id;
    if (deviceId is List) {
      id = deviceId.first;
    } else {
      id = deviceId;
    }

    if (_timer != null) {
      _timer!.cancel();
    }

    _timer = Timer(const Duration(milliseconds: 500), () async {
      try {
        late bool response;
        if (isBatch) {
          response = await DevicesManagementApi()
              .deviceBatchControl(deviceId, code, value);
        } else {
          response = await DevicesManagementApi()
              .deviceControl(deviceId, Status(code: code, value: value));
        }

        if (!response) {
          _revertValueAndEmit(id, code, oldValue, emit);
        }
      } catch (e) {
        _revertValueAndEmit(id, code, oldValue, emit);
      }
    });
  }

  void _updateLocalValue(String code, dynamic value) {
    if (code == 'watersensor_state') {
      deviceStatus = deviceStatus.copyWith(statusPower: value);
    } else if (code == 'battery_percentage') {
      deviceStatus = deviceStatus.copyWith(statusPower: value);
    }
  }

  void _revertValueAndEmit(String deviceId, String code, dynamic oldValue,
      Emitter<SmartPowerState> emit) {
    _updateLocalValue(code, oldValue);
    emit(SmartPowerLoadBatchControll(deviceBatchStatus));
  }

  @override
  Future<void> close() {
    _timer?.cancel();
    return super.close();
  }

  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(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          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);
                });
              },
            ),
          ],
        );
      },
    );
  }

  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 showDialog<DateTime>(
      context: context,
      builder: (BuildContext context) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              height: 350,
              width: 350,
              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 showDialog<DateTime>(
      context: context,
      builder: (BuildContext context) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              height: 350,
              width: 350,
              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();
                          },
                        ),
                        TextButton(
                          child: const Text('OK'),
                          onPressed: () {
                            final selectedDateTime = DateTime(selectedYear);
                            Navigator.of(context).pop(selectedDateTime);
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

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

    return await showDialog<DateTime>(
      context: context,
      builder: (BuildContext context) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              height: 350,
              width: 350,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              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);
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  DateTime? dateTime = DateTime.now();

  String formattedDate = DateFormat('yyyy/MM/dd').format(DateTime.now());

  void checkDayMonthYearSelected(
      SelectDateEvent event, Emitter<SmartPowerState> emit) async {
    Future<DateTime?> Function(BuildContext context)? dateSelector;
    String dateFormat;
    switch (currentIndex) {
      case 0:
        dateSelector = (context) {
          return dayMonthYearPicker(context: context);
        };
        dateFormat = 'yyyy/MM/dd';
        break;
      case 1:
        dateSelector = (context) {
          return selectMonthAndYear(context);
        };
        dateFormat = 'yyyy-MM';
        break;
      case 2:
        dateSelector = (context) {
          return selectYear(context);
        };
        dateFormat = 'yyyy';
        break;
      default:
        return;
    }
    Future.delayed(const Duration(milliseconds: 500), () {
      emit(FakeState());
    });
    // Use the selected picker
    await dateSelector(event.context).then((newDate) {
      if (newDate.toString() == 'null') {
        emit(GetDeviceStatus());
      } else {
        dateTime = newDate;
        add(FilterRecordsByDateEvent(
          selectedDate: newDate!,
          viewType: views[currentIndex],
        ));
      }
      // formattedDate = newDate.toString();
    });
    emit(FilterRecordsState(filteredRecords: energyDataList));
  }

  List<EnergyData> energyDataList = [];
  void _filterRecordsByDate(
      FilterRecordsByDateEvent event, Emitter<SmartPowerState> emit) {
    // emit(SmartPowerLoading());

    if (event.viewType == 'Year') {
      formattedDate = event.selectedDate.year.toString();
      filteredRecords = record
          .where((record) => record.eventTime!.year == event.selectedDate.year)
          .toList();
    } else if (event.viewType == 'Month') {
      formattedDate =
          "${event.selectedDate.year.toString()}-${getMonthShortName(event.selectedDate.month)}";

      filteredRecords = record
          .where((record) =>
              record.eventTime!.year == event.selectedDate.year &&
              record.eventTime!.month == event.selectedDate.month)
          .toList();
    } else if (event.viewType == 'Day') {
      formattedDate =
          "${event.selectedDate.year.toString()}-${getMonthShortName(event.selectedDate.month)}-${event.selectedDate.day}";

      filteredRecords = record
          .where((record) =>
              record.eventTime!.year == event.selectedDate.year &&
              record.eventTime!.month == event.selectedDate.month &&
              record.eventTime!.day == event.selectedDate.day)
          .toList();
    }

    selectDateRange();
    energyDataList = filteredRecords.map((eventDevice) {
      return EnergyData(
        event.viewType == 'Year'
            ? getMonthShortName(
                int.tryParse(DateFormat('MM').format(eventDevice.eventTime!))!)
            : event.viewType == 'Month'
                ? DateFormat('yyyy/MM/dd').format(eventDevice.eventTime!)
                : DateFormat('HH:mm:ss').format(eventDevice.eventTime!),
        double.parse(eventDevice.value!),
      );
    }).toList();
    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(const Duration(days: 1));
    String formattedEndDate = DateFormat('dd/MM/yyyy').format(endDate);
    endChartDate = ' - $formattedEndDate';
  }
}
