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/analytics/blocs/analytics_devices/analytics_devices_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/analytics_device_dropdown.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/device_managment/power_clamp/models/power_clamp_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.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),
                _buildHeader(context),
                Text(
                  'Device ID:',
                  style: context.textTheme.bodySmall?.copyWith(
                    color: ColorsManager.textPrimaryColor,
                    fontWeight: FontWeight.w400,
                    fontSize: 12,
                  ),
                ),
                const SizedBox(height: 6),
                SelectableText(
                  context.watch<AnalyticsDevicesBloc>().state.selectedDevice?.uuid ??
                      'N/A',
                  style: context.textTheme.bodySmall?.copyWith(
                    color: ColorsManager.blackColor,
                    fontWeight: FontWeight.w400,
                    fontSize: 12,
                  ),
                ),
                const Divider(),
                Expanded(
                  flex: 2,
                  child: PowerClampEnergyStatusWidget(
                    status: [
                      PowerClampEnergyStatus(
                        iconPath: Assets.powerActiveIcon,
                        title: 'Active',
                        value: _valueFromCode('EnergyConsumed', generalDataPoints),
                        unit: 'W',
                      ),
                      PowerClampEnergyStatus(
                        iconPath: Assets.voltMeterIcon,
                        title: 'Current',
                        value: _valueFromCode('Current', generalDataPoints),
                        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()),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
          flex: 3,
          child: FittedBox(
            fit: BoxFit.scaleDown,
            alignment: AlignmentDirectional.centerStart,
            child: SelectableText(
              'Smart Power Clamp',
              style: context.textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.w700,
                color: ColorsManager.vividBlue.withValues(alpha: 0.6),
                fontSize: 18,
              ),
            ),
          ),
        ),
        const Spacer(),
        Expanded(
          flex: 2,
          child: FittedBox(
            fit: BoxFit.scaleDown,
            alignment: AlignmentDirectional.centerEnd,
            child: AnalyticsDeviceDropdown(
              onChanged: (value) {
                FetchEnergyManagementDataHelper.loadEnergyConsumptionByPhases(
                  context,
                  powerClampUuid: value.uuid,
                  selectedDate:
                      context.read<AnalyticsDatePickerBloc>().state.monthlyDate,
                );
                FetchEnergyManagementDataHelper.loadRealtimeDeviceChanges(
                  context,
                  deviceUuid: value.uuid,
                );
              },
            ),
          ),
        ),
      ],
    );
  }

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