import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:intl/intl.dart';
import 'package:ln_jq_app/common/model/base_model.dart';
import 'package:ln_jq_app/pages/b_page/site/controller.dart'; // For ReservationModel
import 'package:ln_jq_app/common/styles/theme.dart';

class TimeSlot {
  final TimeOfDay start;
  final TimeOfDay end;

  TimeSlot(this.start, this.end);

  String get display {
    final startStr =
        '${start.hour.toString().padLeft(2, '0')}:${start.minute.toString().padLeft(2, '0')}';
    final endStr =
        '${end.hour.toString().padLeft(2, '0')}:${end.minute.toString().padLeft(2, '0')}';
    return '$startStr - $endStr';
  }
}

class ReservationEditController extends GetxController with BaseControllerMixin {
  late final ReservationModel reservation;
  late final String difference;

  // --- State Variables ---
  final Rx<DateTime> selectedDate = DateTime.now().obs;
  final Rx<TimeOfDay> startTime = TimeOfDay.now().obs;
  final Rx<TimeOfDay> endTime = TimeOfDay.now().obs;
  final TextEditingController amountController = TextEditingController();

  // --- Getters for UI display ---
  String get formattedTimeSlot =>
      '${_formatTimeOfDay(startTime.value)} - ${_formatTimeOfDay(endTime.value)}';

  @override
  void onInit() {
    super.onInit();
    // Expect a Map containing both the reservation and the difference
    final args = Get.arguments as Map<String, dynamic>;
    reservation = args['reservation'] as ReservationModel;
    difference = args['difference'] as String? ?? '0';

    try {
      // Initialize the UI with the data from the passed reservation object
      selectedDate.value = DateFormat('yyyy-MM-dd').parse(reservation.date);

      final startDateTime = DateFormat(
        'yyyy-MM-dd HH:mm:ss',
      ).parse(reservation.startTime);
      startTime.value = TimeOfDay.fromDateTime(startDateTime);

      final endDateTime = DateFormat('yyyy-MM-dd HH:mm:ss').parse(reservation.endTime);
      endTime.value = TimeOfDay.fromDateTime(endDateTime);

      amountController.text = reservation.hydAmount.replaceAll('kg', '');
    } catch (e) {
      showErrorToast("加载预约数据时出错");
      Get.back(); // Go back if data is invalid
    }
  }

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

  /// Reusable time slot picker logic, copied from the reservation creation page.
  void pickTime(BuildContext context) {
    final now = DateTime.now();
    final isToday =
        selectedDate.value.year == now.year &&
        selectedDate.value.month == now.month &&
        selectedDate.value.day == now.day;

    final List<TimeSlot> availableSlots = [];
    for (int i = 0; i < 24; i++) {
      // 每次增加 60 分钟
      final startMinutes = i * 60;
      final endMinutes = startMinutes + 60;

      final startTime = TimeOfDay(hour: startMinutes ~/ 60, minute: startMinutes % 60);
      // 注意：endMinutes % 60 始终为 0，因为间隔是整小时
      final endTime = TimeOfDay(hour: (endMinutes ~/ 60) % 24, minute: endMinutes % 60);

      // 如果不是今天，所有时间段都有效
      if (!isToday) {
        availableSlots.add(TimeSlot(startTime, endTime));
      } else {
        // 如果是今天，需要判断该时间段是否可选
        // 创建时间段的结束时间对象
        final slotEndDateTime = DateTime(
          selectedDate.value.year,
          selectedDate.value.month,
          selectedDate.value.day,
          endTime.hour,
          endTime.minute,
        );

        // 注意：如果是跨天的 00:00 (例如 23:00 - 00:00)，需要将日期加一天，否则 isAfter 判断会出错
        // 但由于我们用的是 endTime.hour % 24，当变成 0 时，日期还是 selectedDate
        // 这里做一个特殊处理：如果 endTime 是 00:00，意味着它实际上是明天的开始
        DateTime realEndDateTime = slotEndDateTime;
        if (endTime.hour == 0 && endTime.minute == 0) {
          realEndDateTime = slotEndDateTime.add(const Duration(days: 1));
        }

        // 只要时间段的结束时间晚于当前时间，这个时间段就是可预约的
        if (realEndDateTime.isAfter(now)) {
          availableSlots.add(TimeSlot(startTime, endTime));
        }
      }
    }

    if (availableSlots.isEmpty) {
      showToast('今天已没有可预约的时间段');
      return;
    }

    // 查找当前选中的时间对应的新列表中的索引
    int initialItem = availableSlots.indexWhere(
      (slot) => slot.start.hour == startTime.value.hour,
    );

    if (initialItem == -1) {
      initialItem = 0;
    }

    TimeSlot tempSlot = availableSlots[initialItem];

    Get.bottomSheet(
      Container(
        height: 300,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16),
            topRight: Radius.circular(16),
          ),
        ),
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  CupertinoButton(
                    onPressed: () {
                      if (Get.isBottomSheetOpen ?? false) {
                        Navigator.of(Get.overlayContext!).pop(); // 更加安全的关闭当前弹窗的方式
                      }
                    },
                    child: const Text(
                      '取消',
                      style: TextStyle(color: CupertinoColors.systemGrey),
                    ),
                  ),
                  CupertinoButton(
                    onPressed: () {
                      startTime.value = tempSlot.start;
                      endTime.value = tempSlot.end;
                      if (Get.isBottomSheetOpen ?? false) {
                        Navigator.of(Get.overlayContext!).pop(); // 更加安全的关闭当前弹窗的方式
                      }
                    },
                    child: const Text(
                      '确认',
                      style: TextStyle(
                        color: AppTheme.themeColor,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const Divider(height: 1, color: Color(0xFFE5E5E5)),
            Expanded(
              child: CupertinoPicker(
                scrollController: FixedExtentScrollController(initialItem: initialItem),
                itemExtent: 40.0,
                onSelectedItemChanged: (index) {
                  tempSlot = availableSlots[index];
                },
                children: availableSlots
                    .map((slot) => Center(child: Text(slot.display)))
                    .toList(),
              ),
            ),
          ],
        ),
      ),
      backgroundColor: Colors.transparent,
    );
  }

  /// This function will be called when the 'Save Changes' button is pressed.
  void updateReservation() async {
    String amountStr = amountController.text.toString();
    if (amountStr.isEmpty) {
      showToast("请输入需要预约的氢量");
      return;
    }
    double amountDouble = (double.tryParse(amountStr) ?? 0.0);
    if (amountDouble <= 0) {
      showToast("预约氢量必须大于0");
      return;
    }
    if (amountDouble > (double.tryParse(difference) ?? 0.0)) {
      showToast('当前最大可预约氢量为$difference(KG)');
      return;
    }

    showLoading("正在保存修改...");

    final dateStr = DateFormat('yyyy-MM-dd').format(selectedDate.value);
    final startTimeStr = '$dateStr ${_formatTimeOfDay(startTime.value)}:00';
    final endTimeStr = '$dateStr ${_formatTimeOfDay(endTime.value)}:00';

    try {
      var responseData = await HttpService.to.post(
        'appointment/orderAddHyd/saveOrUpdate',
        data: {
          'id': reservation.id,
          'stationId': reservation.stationId,
          'startTime': startTimeStr,
          'endTime': endTimeStr,
          'hydAmount': amountStr,
        },
      );

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

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

      if (result.code == 0) {
        showSuccessToast("修改成功");
        //弹窗刷新数据
        Get.back(result: true);
      } else {
        showToast(result.error);
      }
    } catch (e) {
      showErrorToast("保存失败，请稍后再试");
    } finally {
      dismissLoading();
    }
  }

  String _formatTimeOfDay(TimeOfDay time) {
    final hour = time.hour.toString().padLeft(2, '0');
    final minute = time.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  @override
  String get builderId => "reservationeditpage";
}
