import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ln_jq_app/common/styles/theme.dart';
import 'package:ln_jq_app/pages/b_page/history/controller.dart';
import 'package:ln_jq_app/pages/b_page/site/controller.dart'; // Reuse ReservationModel

class HistoryPage extends GetView<HistoryController> {
  const HistoryPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Get.put(HistoryController());

    return Scaffold(
      appBar: AppBar(title: const Text('历史记录'), centerTitle: true),
      body: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          children: [
            _buildFilterCard(context),
            const SizedBox(height: 12),
            _buildSummaryCard(),
            const SizedBox(height: 12),
            _buildListHeader(),
            Expanded(child: _buildHistoryList()),
          ],
        ),
      ),
    );
  }

  Widget _buildFilterCard(BuildContext context) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('时间范围', style: TextStyle(fontSize: 14, color: Colors.grey)),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(child: _buildDateField(context, true)),
                const Padding(
                  padding: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Text('至'),
                ),
                Expanded(child: _buildDateField(context, false)),
              ],
            ),
            const SizedBox(height: 16),
            const Text('车牌号', style: TextStyle(fontSize: 14, color: Colors.grey)),
            const SizedBox(height: 8),
            SizedBox(
              height: 44,
              child: TextField(
                controller: controller.plateNumberController,
                decoration: InputDecoration(
                  hintText: '请输入车牌号',
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                  contentPadding: const EdgeInsets.symmetric(horizontal: 12),
                ),
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: () {
                FocusScope.of(context).unfocus(); // Hide keyboard
                controller.fetchHistoryData();
              },
              icon: const Icon(Icons.search, size: 20),
              label: const Text('查询'),
              style: ElevatedButton.styleFrom(
                minimumSize: const Size(double.infinity, 44),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSummaryCard() {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 20.0),
        child: Obx(
          () => Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSummaryItem('实际加氢总量', controller.totalHydrogen.value, Colors.blue),
              const SizedBox(width: 1, height: 40, child: VerticalDivider()),
              _buildSummaryItem(
                '预约完成次数',
                controller.totalCompletions.value,
                Colors.green,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHistoryList() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(child: CircularProgressIndicator());
      }
      if (!controller.hasData.value) {
        return const Center(child: Text('没有找到相关记录'));
      }
      return ListView.builder(
        itemCount: controller.historyList.length,
        itemBuilder: (context, index) {
          final ReservationModel item = controller.historyList[index];
          return Card(
            margin: const EdgeInsets.only(bottom: 8),
            child: ListTile(
              title: Text('车牌号: ${item.plateNumber}'),
              subtitle: Text.rich(
                TextSpan(
                  children: [
                    TextSpan(
                      text: '加氢站: ${item.stationName}\n',
                      style: TextStyle(fontSize: 16),
                    ),
                    TextSpan(
                      text: '时间: ${item.time}\n',
                      style: TextStyle(fontSize: 16),
                    ),
                    TextSpan(
                      text: '加氢量：',
                    ),
                    TextSpan(
                      text: '${item.amount}',
                      style: TextStyle(fontSize: 16, color: AppTheme.themeColor),
                    ),
                  ],
                ),
              )
              ,
              trailing:
                  // 状态标签
                  _buildStatusChip(item.status),
            ),
          );
        },
      );
    });
  }

  Widget _buildStatusChip(ReservationStatus status) {
    String text;
    Color color;
    switch (status) {
      case ReservationStatus.pending:
        text = '待加氢';
        color = Colors.orange;
        break;
      case ReservationStatus.completed:
        text = '已加氢';
        color = Colors.greenAccent;
        break;
      case ReservationStatus.rejected:
        text = '拒绝加氢';
        color = Colors.red;
        break;
      case ReservationStatus.unadded:
        text = '未加氢';
        color = Colors.red;
        break;
      case ReservationStatus.cancel:
        text = '已取消';
        color = Colors.red;
        break;
      default:
        text = '未知状态';
        color = Colors.grey;
        break;
    }
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.circle, color: color, size: 8),
          const SizedBox(width: 4),
          Text(
            text,
            style: TextStyle(color: color, fontSize: 12, fontWeight: FontWeight.bold),
          ),
        ],
      ),
    );
  }

  Widget _buildDateField(BuildContext context, bool isStart) {
    return Obx(
      () => InkWell(
        onTap: () => controller.pickDate(context, isStart),
        child: Container(
          height: 44,
          padding: const EdgeInsets.symmetric(horizontal: 12),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey.shade400),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(isStart ? controller.formattedStartDate : controller.formattedEndDate),
              const Icon(Icons.calendar_today, size: 18, color: Colors.grey),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSummaryItem(String label, String value, Color color) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(label, style: const TextStyle(color: Colors.grey, fontSize: 14)),
        const SizedBox(height: 8),
        Text(
          value,
          style: TextStyle(color: color, fontSize: 22, fontWeight: FontWeight.bold),
        ),
      ],
    );
  }

  Widget _buildListHeader() {
    return const Padding(
      padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 14.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text('加氢明细', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }
}
