import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:month_picker_dialog/month_picker_dialog.dart';
import 'package:mypoint_flutter_app/extensions/datetime_extensions.dart';
import 'package:mypoint_flutter_app/screen/transaction/transactions_history_viewmodel.dart';
import 'package:mypoint_flutter_app/widgets/custom_empty_widget.dart';
import 'package:mypoint_flutter_app/widgets/image_loader.dart';
import '../../resources/base_color.dart';
import '../../shared/router_gage.dart';
import '../../widgets/custom_navigation_bar.dart';
import 'history/transaction_history_model.dart';
import 'history/transaction_history_response_model.dart';

class TransactionHistoryScreen extends StatefulWidget {
  const TransactionHistoryScreen({super.key});

  @override
  State<TransactionHistoryScreen> createState() => _TransactionHistoryScreenState();
}

class _TransactionHistoryScreenState extends State<TransactionHistoryScreen> {
  final TransactionsHistoryViewModel _viewModel = Get.put(TransactionsHistoryViewModel());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomNavigationBar(title: 'Lịch sử giao dịch'),
      body: Obx(() {
        final summary = _viewModel.historyResponse.value?.summary;
        final items = _viewModel.historyResponse.value?.items ?? [];
        return Column(
          children: [
            _buildCategoryTabs(),
            _buildSummaryBox(summary),
            const SizedBox(height: 8),
            if (items.isEmpty) Expanded(child: Center(child: EmptyWidget(size: Size(160, 160)))),
            Expanded(
              child: ListView.builder(
                physics: const AlwaysScrollableScrollPhysics(),
                itemCount: items.length,
                itemBuilder: (context, index) {
                  final item = items[index];
                  return GestureDetector(
                      onTap: () {
                        Get.toNamed(
                          transactionHistoryDetailScreen,
                          arguments: {"orderId": item.id ?? ""},
                        );
                      },
                      child: _buildTransactionItem(item));
                },
              ),
            ),
          ],
        );
      }),
    );
  }

  Widget _buildCategoryTabs() {
    return SizedBox(
      height: 48,
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        itemCount: _viewModel.categories.value.length,
        separatorBuilder: (_, __) => const SizedBox(width: 8),
        itemBuilder: (context, index) {
          final category = _viewModel.categories.value[index];
          final isSelected = category.code == _viewModel.categorySelected?.code;
          return GestureDetector(
            onTap: () {
              setState(() {
                _viewModel.categorySelected = category;
                _viewModel.getTransactionHistoryResponse();
              });
            },
            child: Chip(
              label: Text(
                category.name ?? '',
                style: TextStyle(color: isSelected ? BaseColor.primary500 : Colors.black54),
              ),
              backgroundColor: isSelected ? Colors.red.shade50 : Colors.grey.shade100,
            ),
          );
        },
      ),
    );
  }

  Widget _buildSummaryBox(TransactionHistorySummaryModel? summary) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            children: [
              Text(
                'Tháng ${_viewModel.date.toFormattedString(format: 'MM/yyyy')}',
                style: TextStyle(color: Colors.black87, fontWeight: FontWeight.bold),
              ),
              const SizedBox(width: 4),
              Text(
                '(${_viewModel.historyResponse.value?.items?.length ?? 0} giao dịch)',
                style: const TextStyle(color: Colors.black54, fontSize: 14),
              ),
              Spacer(),
              GestureDetector(
                onTap: () async {
                  // final picked = await showDatePicker(
                  //   context: context,
                  //   initialDatePickerMode: DatePickerMode.year,
                  //   initialDate: _viewModel.date,
                  //   firstDate: DateTime(1900),
                  //   lastDate: DateTime(2100),
                  // );
                  // if (picked != null) {
                  //   setState(() {
                  //     _viewModel.date = picked;
                  //     _viewModel.getTransactionHistoryResponse();
                  //   });
                  // }
                  showMonthPicker(context: context, initialDate: _viewModel.date, lastDate: DateTime.now()).then((
                    date,
                  ) {
                    if (date != null) {
                      setState(() {
                        _viewModel.date = date;
                        _viewModel.getTransactionHistoryResponse();
                      });
                    }
                  });
                },
                child: Container(
                  padding: const EdgeInsets.all(6),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.black26),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.calendar_today_outlined, size: 16),
                      const SizedBox(width: 2),
                      Text("Tháng"),
                      const SizedBox(width: 2),
                      Icon(Icons.keyboard_arrow_down, size: 20),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            border: Border.all(color: BaseColor.primary200),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                (summary?.total ?? '').isEmpty ? "0" : summary?.total ?? '',
                style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 4),
              Row(
                children: [
                  Text('Giao dịch bằng tiền', style: TextStyle(color: Colors.black87)),
                  const Spacer(),
                  Text(summary?.totalPayCash ?? "0", style: const TextStyle(color: Colors.black87, fontSize: 14)),
                ],
              ),
              Row(
                children: [
                  Text('Giao dịch bằng điểm', style: TextStyle(color: Colors.black87)),
                  const Spacer(),
                  Image.asset('assets/images/ic_point.png', width: 16, height: 16),
                  const SizedBox(width: 2),
                  Text(summary?.totalPayPoint ?? "0", style: const TextStyle(color: Colors.orange, fontSize: 14)),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildTransactionItem(TransactionHistoryModel item) {
    return Column(
      children: [
        ListTile(
          leading: loadNetworkImage(
            url: item.logo ?? '',
            width: 40,
            height: 40,
            fit: BoxFit.cover,
            placeholderAsset: 'assets/images/ic_membership_voucher.png',
          ),
          title: Text(item.name ?? 'Thanh toán mua ưu đãi'),
          subtitle: Text(item.createdAt ?? '', style: const TextStyle(fontSize: 13, color: Colors.black54)),
          trailing: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              if ((item.payCash ?? '').isNotEmpty) Text(item.payCash ?? '0đ', style: TextStyle(fontSize: 14)),
              if ((item.payPoint ?? '').isNotEmpty)
                Row(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Image.asset('assets/images/ic_point.png', width: 16, height: 16),
                    const SizedBox(width: 2),
                    Text(item.payPoint ?? "0", style: const TextStyle(color: Colors.orange, fontSize: 14)),
                  ],
                ),
            ],
          ),
        ),
        Divider(height: 1, color: Colors.grey.shade100, indent: 20, endIndent: 20),
      ],
    );
  }
}
