import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:smart_hotel_app/views/home/device/cubit/device_state.dart';

class PowerCharBlock extends StatelessWidget {
  final DeviceInfo deviceInfo;
  final int selectedTabIndex;
  final ValueChanged<int> onTabChanged;

  const PowerCharBlock({
    super.key,
    required this.deviceInfo,
    required this.selectedTabIndex,
    required this.onTabChanged,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 10.h),
      padding: EdgeInsets.all(25.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25.r),
        color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 20.h,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '24小时功率趋势',
                style: TextStyle(
                  fontSize: 24.sp,
                  color: const Color.fromRGBO(100, 116, 139, 1),
                ),
              ),
              Row(
                children: [
                  _buildTab('功率', 0),
                  _buildTab('温度', 1),
                ],
              ),
            ],
          ),
          SizedBox(
            height: 250.h,
            child: BarChart(
              BarChartData(
                alignment: BarChartAlignment.spaceBetween,
                maxY: _calcMaxY(selectedTabIndex),
                minY: 0,
                groupsSpace: 10,
                barTouchData: BarTouchData(enabled: false),
                gridData: FlGridData(
                  show: true,
                  drawHorizontalLine: true,
                  drawVerticalLine: false,
                  horizontalInterval: _calcInterval(selectedTabIndex),
                  getDrawingHorizontalLine: (value) {
                    return const FlLine(
                      color: Color.fromRGBO(209, 213, 219, 1),
                      strokeWidth: 1.5,
                      dashArray: [5, 5],
                    );
                  },
                ),
                titlesData: FlTitlesData(
                  show: true,
                  rightTitles:
                      const AxisTitles(sideTitles: SideTitles(showTitles: false)),
                  topTitles:
                      const AxisTitles(sideTitles: SideTitles(showTitles: false)),
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      interval: _calcInterval(selectedTabIndex),
                      getTitlesWidget: (value, meta) {
                        return Text(
                          '${value.toInt()}',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: const Color.fromRGBO(156, 163, 175, 1),
                            fontSize: 22.sp,
                          ),
                        );
                      },
                      reservedSize: _leftReservedSize,
                    ),
                  ),
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      interval: 1,
                      getTitlesWidget: (value, meta) {
                        final i = value.toInt();
                        final labels = deviceInfo.timeLabels;
                        if (i < 0 || i >= labels.length) {
                          return const SizedBox.shrink();
                        }
                        if (!_visibleLabelIndices.contains(i)) {
                          return const SizedBox.shrink();
                        }
                        return Padding(
                          padding: EdgeInsets.only(top: 8.h),
                          child: Text(
                            labels[i],
                            style: TextStyle(
                              color: const Color.fromRGBO(156, 163, 175, 1),
                              fontSize: 20.sp,
                            ),
                          ),
                        );
                      },
                      reservedSize: 40,
                    ),
                  ),
                ),
                borderData: FlBorderData(show: false),
                barGroups: _buildBarGroups(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTab(String title, int index) {
    final isSelected = selectedTabIndex == index;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => onTabChanged(index),
      child: Container(
        width: 72.w,
        height: 34.h,
        alignment: Alignment.center,
        decoration: isSelected ? BoxDecoration(
          borderRadius: BorderRadius.circular(8.r),
          color: const Color.fromRGBO(219, 234, 254, 1),
          border: Border.all(
            width: 1.w,
            color: const Color.fromRGBO(73, 149, 234, 0.5),
          )
        ) : null,
        child: Text(
          title,
          style: TextStyle(
            fontSize: 24.sp,
            color: isSelected
                ? const Color.fromRGBO(73, 149, 234, 1)
                : const Color.fromRGBO(100, 116, 139, 1),
          ),
        ),
      ),
    );
  }

  List<BarChartGroupData> _buildBarGroups() {
    final data = selectedTabIndex == 0
        ? deviceInfo.powerData
        : deviceInfo.tempData;
    final Color mainColor = selectedTabIndex == 0
        ? const Color.fromRGBO(80, 162, 255, 1)
        : const Color.fromRGBO(251, 191, 36, 1);

    return List.generate(data.length, (i) {
      if (data[i] == 0) return BarChartGroupData(x: i);

      return BarChartGroupData(
        x: i,
        barRods: [
          BarChartRodData(
            toY: data[i].toDouble(),
            color: mainColor,
            width: 16.w,
            borderRadius: BorderRadius.vertical(top: Radius.circular(8.r)),
          ),
        ],
      );
    }).where((group) => group.barRods.isNotEmpty).toList();
  }

  double _calcMaxY(int index) {
    final data = index == 0 ? deviceInfo.powerData : deviceInfo.tempData;
    if (data.isEmpty) return 100;

    final max = data.reduce((a, b) => a > b ? a : b).toDouble();
    if (max == 0) return 100;

    final raw = max * 1.2;
    final magnitude = pow(10, (log(raw) / ln10).floor()).toDouble();
    final normalized = raw / magnitude;
    final nice =
    normalized <= 1 ? 1 :
    normalized <= 2 ? 2 :
    normalized <= 5 ? 5 : 10;
    return nice * magnitude;
  }

  Set<int> get _visibleLabelIndices {
    final length = deviceInfo.timeLabels.length;
    if (length <= 10) {
      return Set.from(List.generate(length, (i) => i));
    }
    final isOdd = length % 2 == 1;
    if (isOdd) {
      // 基数：7 个标签，首尾都显示，中间 5 个均分 6 段
      final step = (length - 1) / 6;
      final indices = <int>{};
      for (int i = 0; i <= 6; i++) {
        indices.add((step * i).round());
      }
      return indices;
    } else {
      // 偶数：6 个标签，显示首和倒数第二个，中间 4 个均分 5 段
      final step = (length - 2) / 5;
      final indices = <int>{};
      for (int i = 0; i <= 5; i++) {
        indices.add((step * i).round());
      }
      return indices;
    }
  }

  double _calcInterval(int index) {
    return _calcMaxY(index) / 5;
  }

  /// 根据最大数值的位数动态计算左侧保留宽度
  double get _leftReservedSize {
    final maxLabel = _calcMaxY(selectedTabIndex).toInt().toString();
    return maxLabel.length * 8;
  }

}