import 'package:flutter/material.dart';
import 'package:flutter/services.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/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/resources/base_color.dart';
import 'package:mypoint_flutter_app/widgets/custom_toast_message.dart';
import '../../../widgets/custom_empty_widget.dart';
import '../../../widgets/custom_navigation_bar.dart';
import '../../extensions/date_format.dart';
import 'history_point_chart.dart';
import 'history_point_viewmodel.dart';
import 'models/cash_history_model.dart';
import 'models/transaction_history_model.dart';

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

  @override
  State<HistoryPointScreen> createState() => _HistoryPointScreenState();
}

class _HistoryPointScreenState extends State<HistoryPointScreen> {
  late final HistoryPointViewModel _viewModel = Get.put(HistoryPointViewModel());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomNavigationBar(title: 'Lịch sử điểm'),
      body: Obx(() {
        final transactionHistories = _viewModel.historyPoint.value?.historyTransaction ?? [];
        final cashHistories = _viewModel.historyPoint.value?.historyCash ?? [];
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 8),
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [_buildTab('Tích điểm', 0), _buildTab('Tiêu điểm', 1), _buildTab('Cash', 2)],
                ),
              ),
            ),
            Expanded(
              child: RefreshIndicator(
                onRefresh: () => _viewModel.freshData(),
                child: CustomScrollView(
                  physics: const AlwaysScrollableScrollPhysics(),
                  slivers: [
                    if (_viewModel.selectedTabIndex.value == 0)
                      SliverToBoxAdapter(
                        child: MonthlyPointsChart(
                          items: _viewModel.transactionSummary.value?.days ?? [],
                          monthSummary: _viewModel.transactionSummary.value?.month,
                          date: _viewModel.selectedDate,
                          onPrevMonth: () => _viewModel.changeDate(true),
                          onNextMonth: () => _viewModel.changeDate(false),
                          onChangeDate: _showDatePicker,
                        ),
                      ),
                    if (_viewModel.selectedTabIndex.value != 0)
                      _buildHeaderDate(),
                    if (_viewModel.selectedTabIndex.value != 2)
                      _buildTransactionHistoryList(transactionHistories),
                    if (_viewModel.selectedTabIndex.value == 2)
                      _buildCashHistoryList(cashHistories),
                    SliverToBoxAdapter(child: SizedBox(height: 32)),
                  ],
                ),
              ),
            ),
          ],
        );
      }),
    );
  }

  SliverToBoxAdapter _buildHeaderDate() {
    return SliverToBoxAdapter(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              visualDensity: VisualDensity.compact,
              onPressed: () => _viewModel.changeDate(true),
              icon: Icon(Icons.chevron_left, color: Colors.blue[900]),
            ),
            GestureDetector(
              onTap: _showDatePicker,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                child: Text(
                  'Tháng ${_viewModel.selectedDate.month}/${_viewModel.selectedDate.year}',
                  style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15, color: Colors.blue[900]),
                ),
              ),
            ),
            IconButton(
              visualDensity: VisualDensity.compact,
              onPressed: () => _viewModel.changeDate(false),
              icon: Icon(Icons.chevron_right, color: Colors.blue[900]),
            ),
          ],
        ),
      ),
    );
  }

  _showDatePicker() {
    showMonthPicker(context: context, initialDate: _viewModel.selectedDate, lastDate: DateTime.now()).then((date) {
      if (date == null) return;
      _viewModel.selectedDate = date;
      _viewModel.freshData();
    });
  }

  Widget _buildTransactionHistoryList(List<TransactionHistoryModel> transactionHistories) {
    if (transactionHistories.isEmpty) {
      return SliverFillRemaining(hasScrollBody: false, child: Center(child: EmptyWidget()));
    } else {
      return SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
          return _buildTransactionHistoryItem(transactionHistories[index]);
        }, childCount: transactionHistories.length),
      );
    }
  }

  Widget _buildCashHistoryList(List<CashHistoryModel> cashHistories) {
    if (cashHistories.isEmpty) {
      return SliverFillRemaining(hasScrollBody: false, child: Center(child: EmptyWidget()));
    } else {
      return SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
          return _buildCashHistoryItem(cashHistories[index]);
        }, childCount: cashHistories.length),
      );
    }
  }

  Widget _buildCashHistoryItem(CashHistoryModel item) {
    final dateText = item.transactionDatetime ?? '';
    return InkWell(
        onTap: () => {},
        child: Container(
          margin: const EdgeInsets.all(8),
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(
                      dateText,
                      style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.black87),
                    ),
                  ),
                  Text(
                      (item.total?.toInt() ?? 0).money(CurrencyUnit.noneSpace),
                      style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.black87),
                  ),
                  const SizedBox(width: 4),
                  Image.asset('assets/images/ic_point.png', width: 18, height: 18),
                ],
              ),
              const SizedBox(height: 4),
              Row(
                children: [
                  Expanded(
                    child: Text(
                      item.cashTitle.orIfBlank('Giao dịch'),
                      style: const TextStyle(fontSize: 14, color: Colors.black54),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Text(
                      item.status.title,
                      style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: item.status.color),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              const Divider(height: 1, color: Colors.black12),
            ],
          ),
        ),
      );
  }
  
  Widget _buildTransactionHistoryItem(TransactionHistoryModel item) {
    final title = item.transactionTagDescription.orIfBlank('Giao dịch');
    final brand = item.brandName.orIfBlank("MyPoint");
    final redeemTotal = item.redeemTotal?.toInt() ?? 0;
    final rewardTotal = item.rewardTotal?.toInt() ?? 0;
    final adjustTotal = item.adjustTotal?.toInt() ?? 0;
    final value = rewardTotal - redeemTotal + adjustTotal;
    final valueColor = value >= 0 ? const Color(0xFF21C777) : const Color(0xFFFE515A);
    final valueText = '${value > 0 ? '+' : (value < 0 ? '-' : '')}${value.toInt()}';
    final dateText = item.transactionDatetime?.toDate()?.toFormattedString(format: DateFormat.viFull);
    final transactionId = item.transactionSequenceId.orIfBlank('');
    return InkWell(
      onTap: () => {},
      child: Padding(
        padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Colors.blue[900]),
            ),
            const SizedBox(height: 6),
            Row(
              children: [
                Row(
                  children: [
                    SizedBox(
                      width: 24,
                      height: 24,
                      child: ClipOval(
                        child: Image.network(
                          item.brandLogo ?? '',
                          fit: BoxFit.contain,
                          errorBuilder: (_, __, ___) => Image.asset('assets/images/ic_logo.png'),
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(brand, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.blue[900])),
                  ],
                ),
                const Spacer(),
                Row(
                  children: [
                    Text(valueText, style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: valueColor)),
                    const SizedBox(width: 4),
                    Image.asset('assets/images/ic_point.png', width: 24, height: 24),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 6),
            Text(dateText ?? '', style: const TextStyle(fontSize: 13, color: Colors.black87)),
            const SizedBox(height: 8),
            if (transactionId.isNotEmpty)
              Container(
                margin: const EdgeInsets.only(bottom: 8),
                alignment: Alignment.centerLeft,
                child: Row(
                  mainAxisSize: MainAxisSize.max, // ⬅️ fill ngang
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    InkWell(
                      borderRadius: BorderRadius.circular(6),
                      onTap: () {
                        Clipboard.setData(ClipboardData(text: transactionId));
                        showToastMessage('Đã sao chép mã giao dịch');
                      },
                      child: const Padding(
                        padding: EdgeInsets.all(4),
                        child: Icon(Icons.copy, size: 16, color: Color(0xFFFF3D00)),
                      ),
                    ),
                    const SizedBox(width: 4),
                    Expanded(
                      child: SelectableText(transactionId, style: const TextStyle(fontSize: 13, color: Colors.black87)),
                    ),
                  ],
                ),
              ),
            const Divider(height: 1, color: Colors.black12),
          ],
        ),
      ),
    );
  }

  Widget _buildTab(String title, int index) {
    final width = MediaQuery.of(context).size.width-3;
    return GestureDetector(
      onTap: () {
        if (_viewModel.selectedTabIndex.value == index) return;
        _viewModel.selectedTabIndex.value = index;
        _viewModel.freshData();
      },
      child: Obx(() {
        final selected = _viewModel.selectedTabIndex.value == index;
        return SizedBox(
          width: width / 3,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                title,
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: selected ? Colors.red : Colors.black54,
                ),
              ),
              const SizedBox(height: 4),
              // if (selected) Container(height: 2, width: 60, color: Colors.red),
              AnimatedContainer(
                duration: const Duration(milliseconds: 180),
                height: 2,
                width: selected ? 60 : 0,
                color: selected ? Colors.red : Colors.transparent,
              ),
            ],
          ),
        );
      }),
    );
  }
}
