import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:ln_jq_app/common/model/base_model.dart';
import 'package:ln_jq_app/common/styles/theme.dart';
import 'package:ln_jq_app/pages/c_page/reservation/controller.dart';
import 'package:ln_jq_app/pages/c_page/reservation_edit/controller.dart';
import 'package:ln_jq_app/pages/c_page/reservation_edit/view.dart';

//加氢预约列表
class ReservationListBottomSheet extends StatefulWidget {
  const ReservationListBottomSheet({super.key});

  @override
  State<ReservationListBottomSheet> createState() => _ReservationListBottomSheetState();
}

class _ReservationListBottomSheetState extends State<ReservationListBottomSheet> {
  final C_ReservationController _controller = Get.find<C_ReservationController>();

  final Map<String, String> _statusOptions = {
    '': '所有状态', // 增加一个“所有状态”的选项
    '0': '待加氢',
    '1': '加氢完成',
    '2': '未加氢',
    '5': '拒绝加氢',
  };
  String _selectedStatus = ''; // 默认选中 '0' (待加氢)

  @override
  void initState() {
    super.initState();
    //  Widget 初始化时，立即调用接口加载默认状态（待加氢）的数据
    _controller.getReservationList(addStatus: _selectedStatus);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: Get.height * 0.6,
      decoration: const BoxDecoration(
        color: Color.fromRGBO(247, 249, 251, 1),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 构建标题和下拉框
          _buildHeader(),
          // 下拉筛选框
          _buildChoice(),
          //  构建列表（使用 Obx 监听数据变化）
          _buildList(),
        ],
      ),
    );
  }

  Widget _buildChoice() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: _statusOptions.entries.map((entry) {
          bool isSelected = _selectedStatus == entry.key;
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              if (_selectedStatus == entry.key) return;

              // 立即执行刷新逻辑
              _controller.getReservationList(addStatus: entry.key);

              // 先更新本地状态改变 UI 选中效果
              setState(() {
                _selectedStatus = entry.key;
              });
            },
            child: Container(
              margin: const EdgeInsets.only(right: 12),
              padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8),
              decoration: BoxDecoration(
                // 选中色使用深绿色，未选中保持纯白
                color: isSelected ? const Color(0xFF006633) : Colors.white,
                borderRadius: BorderRadius.circular(25),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.04),
                    blurRadius: 6,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Text(
                entry.key == '' ? '全部' : entry.value,
                style: TextStyle(
                  // 未选中文字颜色微调为图片中的灰蓝色
                  color: isSelected ? Colors.white : const Color(0xFFAAB6C3),
                  fontSize: 14.sp,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 构建标题、关闭按钮和下拉筛选框
  Widget _buildHeader() {
    return Container(
      margin: const EdgeInsets.fromLTRB(20, 20, 8, 8),
      child: const Text(
        '我的预约',
        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
      ),
    );
  }

  /// 构建预约列表
  Widget _buildList() {
    return Expanded(
      child: Obx(() {
        if (!_controller.hasReservationData.value) {
          return Container(
            margin: const EdgeInsets.only(top: 40),
            child: TextX.bodyLarge('暂无该状态下的预约', weight: FontWeight.w500),
          );
        }
        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: _controller.reservationList.length,
          itemBuilder: (context, index) {
            final reservation = _controller.reservationList[index];
            return Card(
              color: Colors.white,
              margin: const EdgeInsets.only(bottom: 12.0),
              elevation: 0,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 状态标签
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 5,
                          ),
                          decoration: BoxDecoration(
                            color: reservation.state == "-1"
                                ? Color.fromRGBO(241, 67, 56, 0.1)
                                : Color.fromRGBO(230, 249, 243, 1),
                            borderRadius: BorderRadius.circular(4), // 小圆角
                            // 可以选择去掉边框，或者用极淡的边框
                          ),
                          child: Text(
                            "${reservation.stateName}-${reservation.addStatusName}",
                            style: TextStyle(
                              color: reservation.state == "-1"
                                  ? Color.fromRGBO(241, 67, 56, 0.8)
                                  : Color.fromRGBO(49, 186, 133, 1),
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        Spacer(),
                        //取消预约
                        if (reservation.hasEdit)
                          SizedBox(
                            height: 28, // 限制按钮高度，显得精致
                            child: OutlinedButton(
                              onPressed: () async {
                                var responseData = await HttpService.to.post(
                                  'appointment/orderAddHyd/vehicle-cancel',
                                  data: {'id': reservation.id},
                                );

                                if (responseData == null || responseData.data == null) {
                                  showToast('服务暂不可用，请稍后');
                                  dismissLoading();
                                  return;
                                }

                                var result = BaseModel.fromJson(responseData.data);

                                if (result.code == 0) {
                                  showSuccessToast("已取消");
                                  _controller.getReservationList(
                                    addStatus: _selectedStatus,
                                  );
                                } else {
                                  showToast(result.error);
                                }
                              },
                              style: OutlinedButton.styleFrom(
                                padding: const EdgeInsets.symmetric(horizontal: 12),
                                side: BorderSide(color: Colors.grey.shade400),
                                shape: const StadiumBorder(),
                              ),
                              child: Text(
                                '取消预约',
                                style: TextStyle(
                                  color: Colors.grey.shade600,
                                  fontSize: 11.sp,
                                ),
                              ),
                            ),
                          ),
                        SizedBox(width: 10.w),
                        // 修改按钮 (仅在 hasEdit 为 true 时显示)
                        if (reservation.hasEdit)
                          SizedBox(
                            height: 28,
                            child: OutlinedButton(
                              onPressed: () async {
                                var result = await Get.to(
                                  () => ReservationEditPage(),
                                  arguments: {
                                    'reservation': reservation,
                                    'difference': _controller.difference,
                                  },
                                  binding: BindingsBuilder(() {
                                    Get.put(ReservationEditController());
                                  }),
                                  preventDuplicates: false,
                                );
                                if (result == true) {
                                  _controller.getReservationList(
                                    addStatus: _selectedStatus,
                                  );
                                }
                              },
                              style: OutlinedButton.styleFrom(
                                padding: const EdgeInsets.symmetric(horizontal: 12),
                                side:  BorderSide(color: AppTheme.themeColor),
                                shape: const StadiumBorder(),
                                backgroundColor: Colors.white,
                              ),
                              child:  Text(
                                '修改',
                                style: TextStyle(color: AppTheme.themeColor, fontSize: 11.sp),
                              ),
                            ),
                          ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    _buildDetailRow('车牌号:', reservation.plateNumber),
                    _buildDetailRow('预约日期:', reservation.date),
                    _buildDetailRow('预约氢量:', "${reservation.hydAmount} KG"),
                    _buildDetailRow('加氢站:', reservation.stationName),
                    _buildDetailRow('开始时间:', reservation.startTime),
                    _buildDetailRow('结束时间:', reservation.endTime),
                    _buildDetailRow('联系人:', reservation.contacts),
                    _buildDetailRow('联系电话:', reservation.phone),
                    reservation.addStatus == "5"
                        ? _buildDetailRow('拒绝原因:', reservation.rejectReason)
                        : SizedBox(),
                  ],
                ),
              ),
            );
          },
        );
      }),
    );
  }

  /// 构建详情行 (这是一个辅助Widget)
  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              color: Color.fromRGBO(51, 51, 51, 0.6),
              fontSize: 14.sp,
              fontWeight: FontWeight.w400,
            ),
          ),
          const SizedBox(width: 8),
          Text(
            value,
            style: TextStyle(
              color: label.contains("预约氢量:")
                  ? Color.fromRGBO(27, 168, 85, 1)
                  : Color.fromRGBO(51, 51, 51, 1),
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }
}
