import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:ln_jq_app/common/login_util.dart';
import 'package:ln_jq_app/pages/b_page/history/controller.dart';
import 'package:ln_jq_app/pages/b_page/site/controller.dart';

class HistoryPage extends GetView<HistoryController> {
  const HistoryPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HistoryController>(
      init: HistoryController(),
      id: 'history',
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFF7F8FA),
          appBar: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios, color: Colors.black, size: 20),
              onPressed: () => Get.back(),
            ),
            title: _buildSearchBox(),
          ),
          body: Column(
            children: [
              _buildFilterBar(),
              _buildSummaryCard(),
              Expanded(child: _buildHistoryList()),
            ],
          ),
        );
      },
    );
  }

  Widget _buildSearchBox() {
    return Container(
      height: 36,
      decoration: BoxDecoration(
        color: const Color(0xFFF2F3F5),
        borderRadius: BorderRadius.circular(18),
      ),
      child: TextField(
        controller: controller.plateNumberController,
        onSubmitted: (v) => controller.refreshData(),
        decoration: const InputDecoration(
          hintText: '搜索车牌号',
          hintStyle: TextStyle(color: Color(0xFFBBBBBB), fontSize: 14),
          prefixIcon: Icon(Icons.search_sharp, color: Color(0xFFBBBBBB), size: 20),
          border: InputBorder.none,
          contentPadding: EdgeInsets.only(bottom: 12),
        ),
      ),
    );
  }

  Widget _buildFilterBar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: controller.statusOptions.entries.map((entry) {
                  return Obx(() {
                    bool isSelected = controller.selectedStatus.value == entry.key;
                    return GestureDetector(
                      onTap: () => controller.onStatusSelected(entry.key),
                      child: Container(
                        margin: const EdgeInsets.only(right: 12),
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
                        decoration: BoxDecoration(
                          color: isSelected ? const Color(0xFF006633) : Colors.white,
                          borderRadius: BorderRadius.circular(15),
                        ),
                        child: Text(
                          entry.value,
                          style: TextStyle(
                            color: isSelected
                                ? Colors.white
                                : Color.fromRGBO(148, 163, 184, 1),
                            fontSize: 12.sp,
                            fontWeight: isSelected ? FontWeight.bold : FontWeight.w600,
                          ),
                        ),
                      ),
                    );
                  });
                }).toList(),
              ),
            ),
          ),
          _buildTimeFilterIcon(),
        ],
      ),
    );
  }

  Widget _buildTimeFilterIcon() {
    return PopupMenuButton<String>(
      icon: LoginUtil.getAssImg("ic_ex_menu@2x"),
      onSelected: controller.onDateTypeSelected,
      itemBuilder: (context) => [
        const PopupMenuItem(value: 'week', child: Text('最近一周')),
        const PopupMenuItem(value: 'month', child: Text('最近一月')),
        const PopupMenuItem(value: 'three_month', child: Text('最近三月')),
      ],
    );
  }

  Widget _buildSummaryCard() {
    return Container(
      margin: const EdgeInsets.only(left: 16, right: 16,bottom: 12),
      padding: const EdgeInsets.all(20),
      height: 160,
      width: double.infinity,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(24),
        image: const DecorationImage(
          image: AssetImage('assets/images/history_bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('加氢站', style: TextStyle(color: Colors.white70, fontSize: 12)),
          Text(
            controller.stationName,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const Spacer(),
          Obx(
            () => Row(
              children: [
                _buildSummaryItem('实际加氢量', '${controller.totalHydrogen.value} Kg'),
                const SizedBox(width: 40),
                _buildSummaryItem('预约完成次数', '${controller.totalCompletions.value} 次'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSummaryItem(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: const TextStyle(color: Colors.white60, fontSize: 12)),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  Widget _buildHistoryList() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(child: CircularProgressIndicator());
      }
      if (controller.historyList.isEmpty) {
        return const Center(
          child: Text('暂无相关记录', style: TextStyle(color: Color(0xFF999999))),
        );
      }
      return ListView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        itemCount: controller.historyList.length,
        itemBuilder: (context, index) {
          return _buildHistoryItem(controller.historyList[index]);
        },
      );
    });
  }

  Widget _buildHistoryItem(ReservationModel item) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '车牌号',
                    style: TextStyle(
                      color: Color.fromRGBO(148, 163, 184, 1),
                      fontSize: 12.sp,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    item.plateNumber,
                    style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
              _buildStatusBadge(item.status),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              _buildInfoColumn('加氢时间：', item.time),
              _buildInfoColumn('加氢量', '${item.amount} Kg', isRight: true),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildInfoColumn(String label, String value, {bool isRight = false}) {
    return Expanded(
      child: Column(
        crossAxisAlignment: isRight ? CrossAxisAlignment.end : CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: TextStyle(color: Color.fromRGBO(148, 163, 184, 1), fontSize: 12.sp),
          ),
          const SizedBox(height: 4),
          Text(
            value,
            style: TextStyle(
              fontSize: isRight ? 16 : 13,
              fontWeight: isRight ? FontWeight.bold : FontWeight.normal,
              color: const Color(0xFF333333),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatusBadge(ReservationStatus status) {
    String text = '未知';
    Color bgColor = Colors.grey.shade100;
    Color textColor = Colors.grey;

    switch (status) {
      case ReservationStatus.pending:
        text = '待加氢';
        bgColor = const Color(0xFFFFF7E8);
        textColor = const Color(0xFFFF9800);
        break;
      case ReservationStatus.completed:
        text = '已加氢';
        bgColor = const Color(0xFFE8F5E9);
        textColor = const Color(0xFF4CAF50);
        break;
      case ReservationStatus.rejected:
        text = '拒绝加氢';
        bgColor = const Color(0xFFFFEBEE);
        textColor = const Color(0xFFF44336);
        break;
      case ReservationStatus.unadded:
        text = '未加氢';
        bgColor = const Color(0xFFFFEBEE);
        textColor = const Color(0xFFF44336);
        break;
      case ReservationStatus.cancel:
        text = '已取消';
        bgColor = const Color(0xFFFFEBEE);
        textColor = const Color(0xFFF44336);
        break;
      default:
        text = '未知状态';
        bgColor = Colors.grey;
        textColor = Colors.grey;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: textColor.withOpacity(0.3)),
      ),
      child: Text(
        text,
        style: TextStyle(color: textColor, fontSize: 12, fontWeight: FontWeight.bold),
      ),
    );
  }
}
