import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:smart_hotel_app/routes/app_router.gr.dart';

class WeeklyPowerChart extends StatelessWidget {
  final Map<String, dynamic> weeklyPowerUsage;

  const WeeklyPowerChart({super.key, required this.weeklyPowerUsage});

  List<FlSpot> get _spots =>
      (weeklyPowerUsage['spots'] as List<dynamic>?)?.cast<FlSpot>() ?? [];

  List<String> get _timeLabels =>
      (weeklyPowerUsage['timeLabels'] as List<dynamic>?)?.cast<String>() ?? [];

  double get _minX => 0;

  double get _maxX => _spots.length > 1
      ? (_spots.length - 1).toDouble()
      : 1;

  double get _minY => 0;

  double get _maxY {
    final raw = (weeklyPowerUsage['maxValue'] as num?)?.toDouble() ?? 100;
    // 留 10% 余量，防止顶部标签贴边
    return raw * 1.1;
  }

  double get _horizontalInterval => _maxY / 5;

  double get _bottomInterval {
    final len = _spots.length;
    if (len <= 1) return 1;
    if (len <= 7) return 1;
    if (len <= 14) return 2;
    return (len - 1) / 4;
  }

  String _formatBottomTitle(double value) {
    final index = value.toInt();
    if (index < 0 || index >= _timeLabels.length) return '';
    return _timeLabels[index];
  }

  String _formatLeftTitle(double value) {
    return '${value.toInt()}';
  }

  /// 根据最大数值的位数动态计算左侧保留宽度
  double get _leftReservedSize {
    final maxLabel = _maxY.toInt().toString();
    // 每位数字约 10px（22.sp 字号）
    return maxLabel.length * 8;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        context.pushRoute(const ReportEnergyDetailRoute());
      },
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 28.w, vertical: 28.h),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(24.r),
          color: Colors.white,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 20.h,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '${weeklyPowerUsage['title']} (${weeklyPowerUsage['unit']})',
                  style: TextStyle(
                    fontSize: 28.sp,
                    fontWeight: FontWeight.normal,
                    color: const Color.fromRGBO(107, 114, 128, 1),
                  ),
                ),
                Row(
                  spacing: 8.w,
                  children: [
                    Text(
                      weeklyPowerUsage['dateRange'] as String? ?? '',
                      style: TextStyle(
                        fontSize: 24.sp,
                        color: const Color.fromRGBO(156, 163, 175, 1),
                      ),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      size: 24.sp,
                      color: const Color.fromRGBO(156, 163, 175, 1),
                    ),
                  ],
                ),
              ],
            ),
            Container(
              height: 200.h,
              padding: EdgeInsets.only(right: 28.w),
              child: LineChart(
                LineChartData(
                  gridData: FlGridData(
                    show: true,
                    drawHorizontalLine: true,
                    drawVerticalLine: false,
                    horizontalInterval: _horizontalInterval,
                    getDrawingHorizontalLine: (value) {
                      return const FlLine(
                        color: Color.fromRGBO(209, 213, 219, 1),
                        strokeWidth: 2,
                        dashArray: [5, 5],
                      );
                    },
                  ),
                  titlesData: FlTitlesData(
                    rightTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    topTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    bottomTitles: AxisTitles(
                      sideTitles: SideTitles(
                        showTitles: true,
                        interval: _bottomInterval,//刻度间隔
                        getTitlesWidget: (value, meta) {
                          return Padding(
                            padding: EdgeInsets.only(top: 8.h),
                            child: Text(
                              _formatBottomTitle(value),
                              style: TextStyle(
                                fontSize: 22.sp,
                                color: const Color.fromRGBO(156, 163, 175, 1),
                              ),
                            ),
                          );
                        },
                        reservedSize: 20,//轴标签预留的外部空间
                      ),
                    ),
                    leftTitles: AxisTitles(
                      sideTitles: SideTitles(
                        showTitles: true,
                        interval: _horizontalInterval,
                        getTitlesWidget: (value, meta) {
                          return Text(
                            _formatLeftTitle(value),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              color: const Color.fromRGBO(156, 163, 175, 1),
                              fontSize: 22.sp,
                            ),
                          );
                        },
                        reservedSize: _leftReservedSize,
                      ),
                    ),
                  ),
                  borderData: FlBorderData(show: false),
                  minX: _minX,
                  maxX: _maxX,
                  minY: _minY,
                  maxY: _maxY,
                  lineBarsData: [
                    LineChartBarData(
                      spots: _spots,
                      isCurved: true,
                      color: const Color.fromRGBO(59, 130, 246, 1),
                      barWidth: 3,
                      isStrokeCapRound: true,
                      dotData: const FlDotData(show: false),
                      belowBarData: BarAreaData(
                        show: true,
                        gradient: const LinearGradient(
                          colors: [
                            Color.fromRGBO(191, 219, 254, 1),
                            Color.fromRGBO(219, 234, 254, 0.1),
                          ],
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
