import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fl_chart/fl_chart.dart';

class HourlyChartBlock extends StatelessWidget {
  final List<double> hourlyData;
  final double maxValue;
  final List<String> timeLabels;

  const HourlyChartBlock({
    super.key,
    required this.hourlyData,
    required this.maxValue,
    required this.timeLabels,
  });

  double get _chartMaxY {
    final listMax =
        hourlyData.isEmpty ? 0.0 : hourlyData.reduce((a, b) => a > b ? a : b);
    final raw = maxValue > listMax ? maxValue : listMax;
    if (raw <= 0) return 100;
    // 留 10% 余量
    return raw * 1.1;
  }

  double get _chartInterval => _chartMaxY / 5;

  Set<int> get _visibleLabelIndices {
    final length = hourlyData.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;
    }
  }

  String _formatTimeLabel(int index) {
    if (index < 0 || index >= timeLabels.length) return '';
    final label = timeLabels[index];
    return label;

    // "00:00:00" / "00:00" → 只取整点小时，去掉前导 0
    // final parts = label.split(':');
    // final hour = parts.isNotEmpty ? parts[0] : label;
    // return '${int.tryParse(hour) ?? 0}';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(24.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '今日逐时用电',
            style: TextStyle(
              color: const Color.fromRGBO(100, 116, 139, 1),
              fontSize: 24.sp,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 20.h),
          SizedBox(
            height: 200.h,
            child: BarChart(
                BarChartData(
                  alignment: BarChartAlignment.spaceBetween,
                  maxY: _chartMaxY,
                  minY: 0,
                  barTouchData: BarTouchData(enabled: false),
                  titlesData: FlTitlesData(
                    show: true,
                    rightTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    topTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    bottomTitles: AxisTitles(
                      sideTitles: SideTitles(
                        showTitles: true,
                        interval: 1,
                        reservedSize: 30,
                        getTitlesWidget: (value, meta) {
                          final i = value.toInt();
                          if (!_visibleLabelIndices.contains(i)) {
                            return const SizedBox.shrink();
                          }
                          final label = _formatTimeLabel(i);
                          return Padding(
                            padding: EdgeInsets.only(top: 8.h),
                            child: Text(
                              label,
                              style: TextStyle(
                                fontSize: 20.sp,
                                color: const Color.fromRGBO(156, 163, 175, 1),
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                    leftTitles: AxisTitles(
                      sideTitles: SideTitles(
                        showTitles: true,
                        interval: _chartInterval,
                        reservedSize: 55,
                        getTitlesWidget: (value, meta) {
                          return Text(
                            '${value.toInt()}',
                            style: TextStyle(
                              color: const Color.fromRGBO(156, 163, 175, 1),
                              fontSize: 20.sp,
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                  borderData: FlBorderData(show: false),
                  gridData: FlGridData(
                    show: true,
                    drawVerticalLine: false,
                    horizontalInterval: _chartInterval,
                    getDrawingHorizontalLine: (value) {
                      return const FlLine(
                        color: Color.fromRGBO(209, 213, 219, 1),
                        strokeWidth: 1.5,
                        dashArray: [5, 5],
                      );
                    },
                  ),
                  barGroups: _buildBarGroups(),
                ),
              ),
          ),
        ],
      ),
    );
  }

  List<BarChartGroupData> _buildBarGroups() {
    return hourlyData.asMap().entries.map((entry) {
      final index = entry.key;
      final value = entry.value;
      if (value == 0) return BarChartGroupData(x: index);
      return BarChartGroupData(
        x: index,
        barRods: [
          BarChartRodData(
            toY: value,
            color: const Color.fromRGBO(59, 130, 246, 1),
            width: 12.w,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(4),
              topRight: Radius.circular(4),
            ),
          ),
        ],
      );
    }).toList();
  }
}
