import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/power_clamp_phase.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 PowerClampPhasesDataWidget extends StatelessWidget {
  const PowerClampPhasesDataWidget({
    required this.phaseA,
    required this.phaseB,
    required this.phaseC,
    super.key,
  });

  final Phase? phaseA;
  final Phase? phaseB;
  final Phase? phaseC;

  @override
  Widget build(BuildContext context) {
    final phases = [phaseA, phaseB, phaseC];

    return Container(
      width: double.infinity,
      decoration: secondarySection.copyWith(boxShadow: const []),
      child: Row(
        children: List.generate(5, (index) {
          if (index.isOdd) return _buildSeparator();
          final phaseIndex = index ~/ 2;
          final phase = phases[phaseIndex];
          final phaseSuffix = ['A', 'B', 'C'][phaseIndex];

          return Expanded(
            child: Padding(
              padding: const EdgeInsetsDirectional.symmetric(horizontal: 14),
              child: Column(
                spacing: 4,
                children: [
                  const SizedBox(height: 8),
                  FittedBox(
                    fit: BoxFit.scaleDown,
                    alignment: AlignmentDirectional.center,
                    child: Text(
                      'Phase ${phaseIndex + 1}',
                      style: context.textTheme.titleLarge?.copyWith(
                        color: ColorsManager.textPrimaryColor,
                        fontWeight: FontWeight.w700,
                        fontSize: 20,
                      ),
                    ),
                  ),
                  PowerClampPhase(
                    iconPath: Assets.powerActiveIcon,
                    title: 'Active Power',
                    value: _valueFromCode(
                      code: 'ActivePower$phaseSuffix',
                      points: phase?.dataPoints,
                    ),
                    unit: 'W',
                  ),
                  PowerClampPhase(
                    iconPath: Assets.voltageIcon,
                    title: 'Voltage',
                    value: _valueFromCode(
                      code: 'Voltage$phaseSuffix',
                      points: phase?.dataPoints,
                    ),
                    unit: 'V',
                  ),
                  PowerClampPhase(
                    iconPath: Assets.voltMeterIcon,
                    title: 'Current',
                    value: _valueFromCode(
                      code: 'Current$phaseSuffix',
                      points: phase?.dataPoints,
                    ),
                    unit: 'A',
                  ),
                  PowerClampPhase(
                    iconPath: Assets.speedoMeter,
                    title: 'Power Factor',
                    value: _valueFromCode(
                      code: 'PowerFactor$phaseSuffix',
                      points: phase?.dataPoints,
                    ),
                  ),
                  const SizedBox(height: 8),
                ],
              ),
            ),
          );
        }),
      ),
    );
  }

  Widget _buildSeparator() {
    return Container(
      height: double.infinity,
      width: 1,
      decoration: const BoxDecoration(
        boxShadow: [
          BoxShadow(
            color: Color.fromARGB(20, 0, 0, 0),
            offset: Offset(1, 0),
            blurRadius: 1,
          ),
          BoxShadow(
            color: Color.fromARGB(30, 0, 0, 0),
            offset: Offset(-2, 0),
            blurRadius: 1,
          ),
        ],
      ),
    );
  }

  String _valueFromCode({
    required String code,
    required List<DataPoint>? points,
  }) {
    final element = points?.firstWhere(
      (e) => e.code == code,
      orElse: () => DataPoint(value: '--'),
    );
    final value = element?.value;
    if (code.contains('Current')) {
      return _formatCurrentValue(value?.toString());
    }
    if (code.contains('PowerFactor')) {
      return _formatPowerFactor(value?.toString());
    }
    if (code.contains('Voltage')) {
      return _formatVoltage(value?.toString());
    }
    return value?.toString() ?? '--';
  }

  String _formatCurrentValue(String? value) {
    if (value == null) return '--';
    String str = value;
    if (str.isEmpty || str == '--') return '--';
    str = str.replaceAll(RegExp(r'[^0-9]'), '');
    if (str.isEmpty) return '--';
    if (str.length == 1) return '${str[0]}.0';
    return '${str[0]}.${str.substring(1)}';
  }

  String _formatPowerFactor(String? value) {
    if (value == null) return '--';
    String str = value;
    if (str.isEmpty || str == '--') return '--';
    str = str.replaceAll(RegExp(r'[^0-9]'), '');
    if (str.isEmpty) return '--';
    final intValue = int.tryParse(str);
    if (intValue == null) return '--';
    final doubleValue = intValue / 100;
    return doubleValue.toStringAsFixed(2);
  }

  String _formatVoltage(String? value) {
    if (value == null) return '--';
    String str = value;
    if (str.isEmpty || str == '--') return '--';
    str = str.replaceAll(RegExp(r'[^0-9]'), '');
    if (str.isEmpty) return '--';
    if (str.length == 1) return '0.${str[0]}';
    return '${str.substring(0, str.length - 1)}.${str.substring(str.length - 1)}';
  }
}
