import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/widgets/image_loader.dart';
import '../../../widgets/custom_empty_widget.dart';
import '../../widgets/custom_navigation_bar.dart';
import 'history_point_cashback_viewmodel.dart';
import 'models/history_point_cashback_model.dart';

// TODO check api response
class HistoryPointCashBackScreen extends StatefulWidget {
  const HistoryPointCashBackScreen({super.key});

  @override
  State<HistoryPointCashBackScreen> createState() => _HistoryPointCashBackScreenState();
}

class _HistoryPointCashBackScreenState extends State<HistoryPointCashBackScreen> {
  late final HistoryPointCashBackViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = Get.put(HistoryPointCashBackViewModel());
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: CustomNavigationBar(title: "Lịch sử hoàn điểm"),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildTab('Chờ xử lý', 0),
              _buildTab('Tạm duyệt', 1),
              _buildTab('Đã hoàn', 2),
              _buildTab('Đã huỷ', 3),
            ],
          ),
          const Divider(height: 1),
          Obx(
            () => Padding(
              padding: const EdgeInsets.only(left: 16, top: 16),
              child: Row(
                children: [
                  Text(
                    "Tổng số điểm ${_viewModel.selectedTag.tag.toLowerCase()}:",
                    style: const TextStyle(color: Colors.black87, fontSize: 17, fontWeight: FontWeight.w600),
                  ),
                  SizedBox(width: 4),
                  Image.asset("assets/images/ic_point.png", height: 18),
                  SizedBox(width: 4),
                  Text(
                    (_viewModel.pointCashBackData.value?.points ?? 0).money(CurrencyUnit.noneSpace),
                    style: const TextStyle(color: Colors.orange, fontSize: 18, fontWeight: FontWeight.w600),
                  ),
                ],
              ),
            ),
          ),
          if (_viewModel.orders.isEmpty)
            Expanded(child: EmptyWidget(size: Size(screenWidth / 2, screenWidth / 2)))
          else
            Obx(
              () => Expanded(
                child: RefreshIndicator(
                  onRefresh: () async {
                    _viewModel.freshData(isRefresh: true);
                  },
                  child: ListView.builder(
                    padding: const EdgeInsets.all(12),
                    itemCount: _viewModel.orders.length,
                    itemBuilder: (_, index) {
                      if (index >= _viewModel.orders.length) {
                        _viewModel.freshData(isRefresh: false);
                        return const Center(
                          child: Padding(padding: EdgeInsets.all(16), child: CircularProgressIndicator()),
                        );
                      }
                      final order = _viewModel.orders[index];
                      return _buildVoucherItem(order);
                    },
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildTab(String title, int index) {
    return GestureDetector(
      onTap: () => _viewModel.selectTab(index),
      child: Obx(
        () => Padding(
          padding: const EdgeInsets.only(top: 8),
          child: Column(
            children: [
              Text(
                title,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: _viewModel.selectedTabIndex.value == index ? FontWeight.w600 : FontWeight.w500,
                  color: _viewModel.selectedTabIndex.value == index ? Colors.red : Colors.black54,
                ),
              ),
              const SizedBox(height: 4),
              if (_viewModel.selectedTabIndex.value == index) Container(height: 2, width: 60, color: Colors.red),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildVoucherItem(HistoryPointCashBackOrderModel item) {
    return Obx(
      () => Container(
        margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 0),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey.shade200),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(6),
                  child: loadNetworkImage(
                    url: item.logo,
                    height: 32,
                    width: 32,
                    placeholderAsset: "assets/images/ic_logo.png",
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text("Mã đơn hàng: ${item.code}", style: const TextStyle(fontWeight: FontWeight.bold)),
                      const SizedBox(height: 2),
                      Text("HSD: ${item.timeShow}", style: TextStyle(fontSize: 12, color: Colors.black54)),
                    ],
                  ),
                ),
                Center(
                  child: Text(
                    _viewModel.selectedTag.tag,
                    style: TextStyle(color: _viewModel.selectedTag.color, fontWeight: FontWeight.w600, fontSize: 12),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Divider(height: 1, color: Colors.grey.shade200),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('Giá trị đơn hàng', style: TextStyle(color: Colors.black54)),
                Text(
                  (item.price ?? 0).money(CurrencyUnit.VND),
                  style: const TextStyle(color: Colors.red, fontWeight: FontWeight.w500),
                ),
              ],
            ),
            const SizedBox(height: 6),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('Số lượng sản phẩm', style: TextStyle(color: Colors.black54)),
                Text('${item.productQuantity}', style: const TextStyle(fontWeight: FontWeight.w500)),
              ],
            ),
            const SizedBox(height: 6),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('Điểm ${_viewModel.selectedTag.tag.toLowerCase()}', style: const TextStyle(color: Colors.black54)),
                Row(
                  children: [
                    Image.asset("assets/images/ic_point.png", height: 18),
                    SizedBox(width: 4),
                    Text(
                      item.points.money(CurrencyUnit.noneSpace),
                      style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.w600),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
