import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/power_clamp_bloc/power_clamp_bloc.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_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/features/devices/view/widgets/power_clamp/power_clamp_card.dart';
import 'package:syncrow_app/features/shared_widgets/default_container.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class PowerClampPage extends StatefulWidget {
  final DeviceModel? device;

  const PowerClampPage({super.key, this.device});

  @override
  State<PowerClampPage> createState() => _PowerClampPageState();
}

class _PowerClampPageState extends State<PowerClampPage> {
  final PageController _pageController = PageController();
  int _currentPage = 0;
  static const int _pageCount = 4;
  late PowerClampModel model;
  @override
  void initState() {
    super.initState();
    _pageController.addListener(_handlePageChange);
    model = _initialPowerClampModel();
  }

  void _handlePageChange() {
    int nextPage = _pageController.page?.round() ?? 0;
    if (_currentPage != nextPage) {
      setState(() {
        _currentPage = nextPage;
      });
    }
  }

  @override
  void dispose() {
    _pageController.removeListener(_handlePageChange);
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultScaffold(
      title: widget.device?.name ?? 'Power Clamp',
      child: BlocProvider(
        create: (context) => PowerClampBloc(PCId: widget.device?.uuid ?? '')
          ..add(const PowerClampInitial()),
        child: BlocBuilder<PowerClampBloc, PowerClampState>(
          builder: (context, state) {
            final blocProvider = context.read<PowerClampBloc>();
            List<EnergyData> chartData = [];

            if (state is UpdateState) {
              model = state.powerClampModel;
            } else if (state is EnergyDataState) {
              chartData = state.energyData;
            } else if (state is FilterRecordsState) {
              chartData = state.filteredRecords;
            }

            if (state is PowerClampLoadingState) {
              return const Center(
                child: DefaultContainer(
                  width: 50,
                  height: 50,
                  child: CircularProgressIndicator(),
                ),
              );
            }

            return Column(
              children: [
                Flexible(
                  child: RefreshIndicator(
                    onRefresh: () async {
                      blocProvider.add(const PowerClampInitial());
                    },
                    child: PageView(controller: _pageController, children: [
                      _buildPowerClampCard(
                        phaseType: '',
                        title: 'Total Energy \nConsumption',
                        phase: model.status.general,
                        isGeneral: true,
                        chartData: chartData,
                        blocProvider: blocProvider,
                      ),
                      _buildPowerClampCard(
                        title: 'Phase A Energy \nConsumption',
                        phaseType: 'Phase A consumption',
                        phase: model.status.phaseA,
                        chartData: chartData,
                        blocProvider: blocProvider,
                      ),
                      _buildPowerClampCard(
                        title: 'Phase B Energy \nConsumption',
                        phaseType: 'Phase B consumption',
                        phase: model.status.phaseB,
                        chartData: chartData,
                        blocProvider: blocProvider,
                      ),
                      _buildPowerClampCard(
                        title: 'Phase C Energy \nConsumption',
                        phaseType: 'Phase C consumption',
                        phase: model.status.phaseC,
                        chartData: chartData,
                        blocProvider: blocProvider,
                      ),
                    ]),
                  ),
                ),
                _buildPageIndicator(),
              ],
            );
          },
        ),
      ),
    );
  }

  PowerClampModel _initialPowerClampModel() {
    return PowerClampModel(
      productType: '',
      productUuid: '',
      status: PowerStatus(
        phaseA: Phase(dataPoints: _emptyDataPoints()),
        phaseB: Phase(dataPoints: _emptyDataPoints()),
        phaseC: Phase(dataPoints: _emptyDataPoints()),
        general: Phase(dataPoints: _emptyDataPoints()),
      ),
    );
  }

  List<DataPoint> _emptyDataPoints() {
    return [
      DataPoint(
        code: '',
        customName: '',
        dpId: 0,
        time: 0,
        type: '',
        value: 0,
      ),
    ];
  }

  Widget _buildPowerClampCard({
    required String title,
    required String phaseType,
    required Phase phase,
    bool isGeneral = false,
    required List<EnergyData> chartData,
    required PowerClampBloc blocProvider,
  }) {
    return PowerClampCard(
      dateTimeSelected:
          '${blocProvider.dateTime!.day}/${blocProvider.dateTime!.month}/${blocProvider.dateTime!.year} ${blocProvider.endChartDate}',
      energyConsumption: _getValueOrNA(phase.dataPoints, isGeneral ? 0 : 5),
      title: title,
      phaseType: phaseType,
      isGeneral: isGeneral,
      dateSwitcher: blocProvider.dateSwitcher(),
      formattedDate: blocProvider.formattedDate,
      selectDateEvent: () {
        blocProvider.add(SelectDateEvent(context: context));
      },
      totalActiveGeneral: isGeneral ? _getValueOrNA(phase.dataPoints, 2) : null,
      totalCurrentGeneral: isGeneral ? _getValueOrNA(phase.dataPoints, 1) : null,
      totalFrequencyGeneral: isGeneral ? _getValueOrNA(phase.dataPoints, 4) : null,
      totalFactor: !isGeneral ? _getValueOrNA(phase.dataPoints, 3) : null,
      totalActive: !isGeneral ? _getValueOrNA(phase.dataPoints, 2) : null,
      totalCurrent: !isGeneral ? _getValueOrNA(phase.dataPoints, 1) : null,
      totalVoltage: !isGeneral ? _getValueOrNA(phase.dataPoints, 0) : null,
      chartData: chartData,
      context: context,
    );
  }

  String _getValueOrNA(List<DataPoint> dataPoints, int index) {
    return dataPoints.length > index ? dataPoints[index].value.toString() : 'N/A';
  }

  Widget _buildPageIndicator() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: List.generate(_pageCount, (index) {
          return AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            margin: const EdgeInsets.symmetric(horizontal: 4.0),
            height: 10.0,
            width: _currentPage == index ? 10.0 : 10.0,
            decoration: BoxDecoration(
              color: _currentPage == index ? Colors.grey : ColorsManager.greyColor,
              borderRadius: BorderRadius.circular(5.0),
            ),
          );
        }),
      ),
    );
  }
}
