import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:laki_icu_app/blocs/device_control/device_control_bloc.dart';
import 'package:laki_icu_app/blocs/device_control/device_control_event.dart';
import 'package:laki_icu_app/blocs/device_control/device_control_state.dart';
import 'package:laki_icu_app/models/bo/device_control_bo.dart';

import 'device_control_common.dart';

/// 护理等级面板
class DeviceControlCarePanel extends StatelessWidget {
  const DeviceControlCarePanel({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DeviceControlBloc, DeviceControlState>(
      buildWhen: (previous, current) =>
          previous.data.careLevel != current.data.careLevel,
      builder: (context, state) {
        final currentLevel = state.data.careLevel.currentLevel;

        return DeviceControlPanelFrame(
          backgroundAsset: assetPanelWide,
          padding: EdgeInsets.fromLTRB(30.w, 26.h, 30.w, 24.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const DeviceControlPanelTitle('护理等级'),
              const Spacer(),
              _CareLevelBar(currentLevel: currentLevel),
              SizedBox(height: 24.h),
              Row(
                children: [
                  for (final item in _careLevelItems)
                    Expanded(
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () => context.read<DeviceControlBloc>().add(
                              DeviceControlCareLevelChanged(item.level),
                            ),
                        child: Text(
                          item.label,
                          textAlign: TextAlign.center,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 24.sp,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }
}

class _CareLevelBar extends StatelessWidget {
  const _CareLevelBar({required this.currentLevel});

  final CareLevel currentLevel;

  @override
  Widget build(BuildContext context) {
    final activeIndex = _careLevelItems.indexWhere(
      (item) => item.level == currentLevel,
    );

    return LayoutBuilder(
      builder: (context, constraints) {
        final segmentGap = 4.w;
        final knobSize = 54.w;
        final segmentWidth =
            (constraints.maxWidth - segmentGap * (_careLevelItems.length - 1)) /
                _careLevelItems.length;
        final knobLeft = (segmentWidth + segmentGap) * activeIndex +
            segmentWidth -
            knobSize / 2;

        return SizedBox(
          height: knobSize,
          child: Stack(
            clipBehavior: Clip.none,
            alignment: Alignment.centerLeft,
            children: [
              Positioned(
                left: 0,
                right: 0,
                top: (knobSize - 20.h) / 2,
                child: Row(
                  children: [
                    for (var index = 0;
                        index < _careLevelItems.length;
                        index++) ...[
                      Expanded(
                        child: GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () =>
                              context.read<DeviceControlBloc>().add(
                                    DeviceControlCareLevelChanged(
                                      _careLevelItems[index].level,
                                    ),
                                  ),
                          child: Container(
                            height: 20.h,
                            decoration: BoxDecoration(
                              color: index <= activeIndex
                                  ? _careLevelItems[index].color
                                  : const Color(0xFF6A7481),
                              borderRadius: _segmentRadius(index),
                              boxShadow: index <= activeIndex
                                  ? [
                                      BoxShadow(
                                        color: _careLevelItems[index]
                                            .color
                                            .withValues(alpha: 0.35),
                                        blurRadius: 8.r,
                                      ),
                                    ]
                                  : null,
                            ),
                          ),
                        ),
                      ),
                      if (index < _careLevelItems.length - 1)
                        SizedBox(width: segmentGap),
                    ],
                  ],
                ),
              ),
              Positioned(
                left: knobLeft.clamp(0, constraints.maxWidth - knobSize),
                child: Container(
                  width: knobSize,
                  height: knobSize,
                  decoration: BoxDecoration(
                    color: const Color(0xFFF7F7F7),
                    shape: BoxShape.circle,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.white.withValues(alpha: 0.72),
                        blurRadius: 10.r,
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  BorderRadius _segmentRadius(int index) {
    final radius = Radius.circular(12.r);
    if (index == 0) {
      return BorderRadius.horizontal(left: radius);
    }
    if (index == _careLevelItems.length - 1) {
      return BorderRadius.horizontal(right: radius);
    }
    return BorderRadius.zero;
  }
}

const _careLevelItems = [
  _CareLevelItem('关闭', CareLevel.off, Color(0xFFE5F7FF)),
  _CareLevelItem('三级', CareLevel.level3, Color(0xFF60F2B6)),
  _CareLevelItem('二级', CareLevel.level2, Color(0xFFFFCE1B)),
  _CareLevelItem('一级', CareLevel.level1, Color(0xFFFF8D2E)),
  _CareLevelItem('特级', CareLevel.special, Color(0xFFFF554C)),
];

class _CareLevelItem {
  const _CareLevelItem(this.label, this.level, this.color);

  final String label;
  final CareLevel level;
  final Color color;
}
