import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/analytics/models/power_clamp_energy_status.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/blocs/analytics_date_picker_bloc/analytics_date_picker_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/blocs/power_clamp_info/power_clamp_info_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/blocs/realtime_device_changes/realtime_device_changes_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/energy_consumption_by_phases_chart_box.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/power_clamp_energy_status_widget.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/power_clamp_phases_data_widget.dart';
import 'package:syncrow_web/pages/analytics/widgets/analytics_error_widget.dart';
import 'package:syncrow_web/pages/analytics/widgets/analytics_sidebar_header.dart';
import 'package:syncrow_web/pages/device_managment/power_clamp/models/power_clamp_model.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/style.dart';

class PowerClampEnergyDataWidget extends StatelessWidget {
  const PowerClampEnergyDataWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocListener<RealtimeDeviceChangesBloc, RealtimeDeviceChangesState>(
      listenWhen: (previous, current) =>
          previous.deviceStatusList != current.deviceStatusList ||
          previous.status != current.status,
      listener: (context, state) => context.read<PowerClampInfoBloc>().add(
            UpdatePowerClampStatusEvent(state.deviceStatusList),
          ),
      child: BlocBuilder<PowerClampInfoBloc, PowerClampInfoState>(
        builder: (context, state) {
          final generalDataPoints =
              state.powerClampModel?.status.general.dataPoints ?? [];
          return Container(
            decoration: subSectionContainerDecoration.copyWith(
              borderRadius: BorderRadius.circular(30),
            ),
            padding: const EdgeInsetsDirectional.all(32),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AnalyticsErrorWidget(state.errorMessage),
                AnalyticsSidebarHeader(
                  title: 'Smart Power Clamp',
                  showSpaceUuidInDevicesDropdown: true,
                  onChanged: (device) {
                    FetchEnergyManagementDataHelper.loadEnergyConsumptionByPhases(
                      context,
                      powerClampUuid: device.uuid,
                      selectedDate:
                          context.read<AnalyticsDatePickerBloc>().state.monthlyDate,
                    );
                  },
                ),
                Expanded(
                  flex: 2,
                  child: PowerClampEnergyStatusWidget(
                    status: [
                      PowerClampEnergyStatus(
                        iconPath: Assets.powerActiveIcon,
                        title: 'Active',
                        value: _valueFromCode('ActivePower', generalDataPoints),
                        unit: 'W',
                      ),
                      PowerClampEnergyStatus(
                        iconPath: Assets.voltMeterIcon,
                        title: 'Current',
                        value: _valueFromCode('Current', generalDataPoints)
                            .replaceAllMapped(
                              RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
                              (Match m) => '${m[1]}.',
                            )
                            .replaceAll('.0', ''),
                        unit: 'A',
                      ),
                      PowerClampEnergyStatus(
                        iconPath: Assets.frequencyIcon,
                        title: 'Frequency',
                        value: _valueFromCode('Frequency', generalDataPoints),
                        unit: 'Hz',
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 14),
                Expanded(
                  flex: 4,
                  child: PowerClampPhasesDataWidget(
                    phaseA: state.powerClampModel?.status.phaseA,
                    phaseB: state.powerClampModel?.status.phaseB,
                    phaseC: state.powerClampModel?.status.phaseC,
                  ),
                ),
                const SizedBox(height: 14),
                const Expanded(flex: 3, child: EnergyConsumptionByPhasesChartBox()),
              ],
            ),
          );
        },
      ),
    );
  }

  String _valueFromCode(String code, List<DataPoint> points) {
    return points
        .firstWhere((e) => e.code == code, orElse: () => DataPoint(value: '--'))
        .value
        .toString();
  }
}
