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/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.55,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      child: Column(
        children: [
          // 构建标题和下拉框
          _buildHeader(),
          const Divider(height: 1),
          // 下拉筛选框
          _buildChoice(),
          //  构建列表（使用 Obx 监听数据变化）
          _buildList(),
        ],
      ),
    );
  }

  Container _buildChoice() {
    return Container(
          padding: const EdgeInsets.fromLTRB(20, 8, 0, 0),
          alignment: AlignmentGeometry.centerLeft,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 8),
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: BorderRadius.circular(8),
            ),
            child: DropdownButton<String>(
              value: _selectedStatus,
              underline: const SizedBox.shrink(), // 隐藏下划线
              items: _statusOptions.entries.map((entry) {
                return DropdownMenuItem<String>(
                  value: entry.key,
                  child: Text(entry.value),
                );
              }).toList(),
              onChanged: (newValue) {
                if (newValue != null) {
                  setState(() {
                    _selectedStatus = newValue;
                  });
                  // 当选择新状态时，调用接口刷新数据
                  _controller.getReservationList(addStatus: _selectedStatus);
                }
              },
            ),
          ),
        );
  }

  /// 构建标题、关闭按钮和下拉筛选框
  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 8, 8, 8),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Center(child: const Text('我的预约', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),),
          Align(
            alignment: Alignment.centerRight,
            child: ElevatedButton(
              onPressed: () => Get.back(),
              style: ElevatedButton.styleFrom(
                elevation: 0,
                backgroundColor: Colors.grey[200],
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
              ),
              child: const Text('关闭', style: TextStyle(color: Colors.black54)),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建预约列表
  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: 1,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              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: Colors.blue.shade50, // 淡蓝色背景
                            borderRadius: BorderRadius.circular(4), // 小圆角
                            // 可以选择去掉边框，或者用极淡的边框
                            border: Border.all(color: Colors.blue.shade100),
                          ),
                          child: Text(
                            "${reservation.stateName}-${reservation.addStatusName}",
                            style: TextStyle(
                              color: Colors.blue.shade700,
                              fontSize: 12,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        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: 12),
                              ),
                            ),
                          ),
                        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: const BorderSide(color: Colors.blue), // 蓝色边框
                                shape: const StadiumBorder(),
                                backgroundColor: Colors.white,
                              ),
                              child: const Text(
                                '修改',
                                style: TextStyle(color: Colors.blue, fontSize: 12),
                              ),
                            ),),
                      ],
                    ),
                    const SizedBox(height: 12),
                    _buildDetailRow('车牌号:', reservation.plateNumber),
                    _buildDetailRow('预约日期:', reservation.date),
                    _buildDetailRow('预约氢量:', reservation.hydAmount),
                    _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(
        children: [
          Text(label, style: const TextStyle(color: Colors.grey)),
          const SizedBox(width: 8),
          Expanded(
            child: Text(value, style: const TextStyle(fontWeight: FontWeight.w500)),
          ),
        ],
      ),
    );
  }
}
