import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:vbvs_app/common/color/appConstants.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/pages/sleep_report/chart/SegmentedCirclePainter.dart';
import 'package:EasyDartModule/EasyDartModule.dart' as es;

class SleepScoreWidget extends StatefulWidget {
  var sleepReport;
  SleepScoreWidget({super.key, required this.sleepReport});

  @override
  State<SleepScoreWidget> createState() => _SleepScoreWidgetState();
}

class _SleepScoreWidgetState extends State<SleepScoreWidget> {
  @override
  void setState(VoidCallback callback) {
    super.setState(callback);
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
   try {
      if (widget.sleepReport == null ||
        widget.sleepReport is! Map ||
        widget.sleepReport.isEmpty) {
      return Container();
    }
   
    List showLabel = widget.sleepReport['score']['type'];
    List stages = widget.sleepReport['score']['stages'];
    List<SegmentData> segments = parseSegments(widget.sleepReport);

    return Container(
      width: double.infinity,
      // decoration: BoxDecoration(color: Colors.green),
      child: Padding(
        padding: EdgeInsetsDirectional.fromSTEB(26.rpx, 29.rpx, 26.rpx, 45.rpx),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            Container(
              width: double.infinity,
              decoration: BoxDecoration(),
              child: Row(
                mainAxisSize: MainAxisSize.max,
                children: [
                  Container(
                    decoration: BoxDecoration(),
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          constraints: BoxConstraints(maxWidth: 150.rpx),
                          child: Text(
                            '30天平均分'.tr,
                            style: TextStyle(
                              color: Color(0xFFD3D3D3),
                              fontSize: 26.rpx,
                              letterSpacing: 0.0,
                            ),
                            maxLines: 1,
                          ),
                        ),
                        Text(
                          '${widget.sleepReport['score']?['avg']}',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 48.rpx,
                            letterSpacing: 0.0,
                          ),
                        ),
                      ].divide(SizedBox(height: 56.rpx)),
                    ),
                  ),
                  Expanded(
                    child: Container(
                      decoration: BoxDecoration(),
                      child: SegmentedCircleWithCenterWidget(
                        // segments: [
                        //   SegmentData(color: Colors.red, value: 30),
                        //   SegmentData(color: Colors.green, value: 20),
                        //   SegmentData(color: Colors.blue, value: 40),
                        //   SegmentData(color: Colors.orange, value: 10),
                        // ],
                        segments: segments,
                        strokeWidth: 8,
                        gapAngle: 8,
                        centerWidget: Container(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                "睡眠评分".tr,
                                style: TextStyle(
                                    color: stringToColor("#FFFFFF"),
                                    fontSize:
                                        AppConstants().normal_text_fontSize),
                              ),
                              Text(
                                '${widget.sleepReport['score']?['score']}',
                                style: TextStyle(
                                    color: stringToColor("#FF9F66"),
                                    fontSize: 100.rpx),
                              ),
                            ],
                          ),
                        ),
                        trend: widget.sleepReport['score']?['trend'],
                      ),
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(),
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '睡眠等级'.tr,
                          style: TextStyle(
                            color: Color(0xFFD3D3D3),
                            fontSize: 26.rpx,
                            letterSpacing: 0.0,
                          ),
                        ),
                        Text(
                          '${getSleepLevel(widget.sleepReport)}',
                          style: TextStyle(
                            color: stringToColor("#FF9F66"),
                            fontSize: 48.rpx,
                            letterSpacing: 0.0,
                          ),
                        ),
                      ].divide(SizedBox(height: 56.rpx)),
                    ),
                  ),
                ].divide(SizedBox(
                  width: 33.rpx,
                )),
              ),
            ),
            Wrap(
              spacing: 32.rpx,
              runSpacing: 20.rpx,
              children: showLabel.map<Widget>((item) {
                return Container(
                  padding: EdgeInsets.all(5.rpx),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        width: 20.rpx,
                        height: 20.rpx,
                        decoration: BoxDecoration(
                          color: stringToColor("${item["color"]}"),
                          borderRadius: BorderRadius.circular(10.rpx),
                        ),
                      ),
                      SizedBox(width: 17.rpx),
                      Text(
                        item["name"] + '(' + item['range'] + ")",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 24.rpx,
                        ),
                      ),
                    ],
                  ),
                );
              }).toList(),
            ),
          ],
        ),
      ),
    );
  
   } catch (e) {
      es.EasyDartModule.logger.error("打鼾监测绘制异常${e}");
     return Container();  
   }
  }

  //获取睡眠等级
  String getSleepLevel(sleepReport) {
    if (sleepReport == null ||
        sleepReport['score'] == null ||
        sleepReport['score']['level'] == null ||
        sleepReport['score']['type'] == null) {
      return "未知数据".tr;
    }

    int level = sleepReport['score']['level'];
    List<dynamic> typeList = sleepReport['score']['type'];

    // 在 typeList 中查找 level 匹配的项
    var matched = typeList.firstWhere(
      (item) => item['level'] == level,
      orElse: () => null,
    );

    if (matched != null && matched['name'] != null) {
      return matched['name'];
    }
    return "未知数据".tr;
  }

  List<SegmentData> parseSegments(Map sleepReport) {
    try {
      List stages = sleepReport['score']['stages'] ?? [];
      List typeList = sleepReport['sleepData']['type'] ?? [];

      Map<int, Color> typeColorMap = {
        for (var item in typeList)
          if (item['type'] != null && item['color'] != null)
            item['type']: stringToColor(item['color'])
      };

      // 构造 segments 列表
      List<SegmentData> segments = stages.map<SegmentData>((stage) {
        int type = stage['type'];
        double value = (stage['per'] ?? 0).toDouble();
        Color color = typeColorMap[type] ?? Colors.grey; // fallback 灰色

        return SegmentData(color: color, value: value);
      }).toList();

      return segments;
    } catch (e) {
      return [];
    }
  }
}
