/// Page: Points History Page
///
/// Displays history of points earned and spent transactions.
library;

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:worker/features/loyalty/data/models/loyalty_point_entry_model.dart';
import 'package:worker/features/loyalty/presentation/providers/points_history_provider.dart';

/// Points History Page
///
/// Features:
/// - Filter section with date range picker
/// - List of transaction cards with new design
/// - Each card shows: code, date, description, reference, points change, balance after
class PointsHistoryPage extends ConsumerWidget {
  const PointsHistoryPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;
    // Use unfiltered data for now (mock data)
    final historyAsync = ref.watch(pointsHistoryProvider);
    final filter = ref.watch(pointsHistoryFilterProvider);
    //todo: implement filtering logic in provider later
    //:note: final historyAsync = ref.watch(filteredPointsHistoryProvider);

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        leading: IconButton(
          icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Lịch sử điểm',
          style: TextStyle(color: colorScheme.onSurface),
        ),
        elevation: AppBarSpecs.elevation,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          await ref.read(pointsHistoryProvider.notifier).refresh();
        },
        child: historyAsync.when(
          data: (entries) {
            return ListView(
              padding: const EdgeInsets.all(16),
              children: [
                // Filter Section
                _buildFilterSection(context, ref, colorScheme, filter),

                const SizedBox(height: 16),

                // Empty state or Transaction List
                if (entries.isEmpty)
                  _buildEmptyStateInline(colorScheme)
                else
                  ...entries.map(
                    (entry) => _buildTransactionCard(context, entry, colorScheme),
                  ),
              ],
            );
          },
          loading: () => const CustomLoadingIndicator(),
          error: (error, stack) => _buildErrorState(error, colorScheme),
        ),
      ),
    );
  }

  /// Build filter section with date pickers
  Widget _buildFilterSection(
    BuildContext context,
    WidgetRef ref,
    ColorScheme colorScheme,
    PointsHistoryFilter filter,
  ) {
    final dateFormatter = DateFormat('dd/MM/yyyy');

    return Card(
      elevation: 1,
      margin: EdgeInsets.zero,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'Bộ lọc',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                ),
                FaIcon(FontAwesomeIcons.filter, color: colorScheme.primary, size: 18),
              ],
            ),
            const SizedBox(height: 16),

            // Date range row
            Row(
              children: [
                // Start date
                Expanded(
                  child: _buildDateField(
                    context: context,
                    colorScheme: colorScheme,
                    label: 'Từ ngày',
                    value: filter.startDate,
                    dateFormatter: dateFormatter,
                    onTap: () async {
                      final date = await showDatePicker(
                        context: context,
                        initialDate: filter.startDate ?? DateTime.now(),
                        firstDate: DateTime(2020),
                        lastDate: filter.endDate ?? DateTime.now(),
                      );
                      if (date != null) {
                        ref.read(pointsHistoryFilterProvider.notifier).setStartDate(date);
                      }
                    },
                  ),
                ),
                const SizedBox(width: 12),
                // End date
                Expanded(
                  child: _buildDateField(
                    context: context,
                    colorScheme: colorScheme,
                    label: 'Đến ngày',
                    value: filter.endDate,
                    dateFormatter: dateFormatter,
                    onTap: () async {
                      final date = await showDatePicker(
                        context: context,
                        initialDate: filter.endDate ?? DateTime.now(),
                        firstDate: filter.startDate ?? DateTime(2020),
                        lastDate: DateTime.now(),
                      );
                      if (date != null) {
                        ref.read(pointsHistoryFilterProvider.notifier).setEndDate(date);
                      }
                    },
                  ),
                ),
              ],
            ),

            const SizedBox(height: 12),

            // Quick filter chips
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: [
                  _buildQuickFilterChip(
                    context: context,
                    ref: ref,
                    colorScheme: colorScheme,
                    label: 'Hôm nay',
                    onTap: () {
                      final now = DateTime.now();
                      final today = DateTime(now.year, now.month, now.day);
                      ref.read(pointsHistoryFilterProvider.notifier).setDateRange(today, today);
                    },
                  ),
                  const SizedBox(width: 8),
                  _buildQuickFilterChip(
                    context: context,
                    ref: ref,
                    colorScheme: colorScheme,
                    label: '7 ngày',
                    onTap: () {
                      final now = DateTime.now();
                      final today = DateTime(now.year, now.month, now.day);
                      final weekAgo = today.subtract(const Duration(days: 7));
                      ref.read(pointsHistoryFilterProvider.notifier).setDateRange(weekAgo, today);
                    },
                  ),
                  const SizedBox(width: 8),
                  _buildQuickFilterChip(
                    context: context,
                    ref: ref,
                    colorScheme: colorScheme,
                    label: '30 ngày',
                    onTap: () {
                      final now = DateTime.now();
                      final today = DateTime(now.year, now.month, now.day);
                      final monthAgo = today.subtract(const Duration(days: 30));
                      ref.read(pointsHistoryFilterProvider.notifier).setDateRange(monthAgo, today);
                    },
                  ),
                  const SizedBox(width: 8),
                  _buildQuickFilterChip(
                    context: context,
                    ref: ref,
                    colorScheme: colorScheme,
                    label: 'Năm nay',
                    onTap: () {
                      final now = DateTime.now();
                      ref.read(pointsHistoryFilterProvider.notifier).setDateRange(
                        DateTime(now.year, 1, 1),
                        DateTime(now.year, 12, 31),
                      );
                    },
                  ),
                  const SizedBox(width: 8),
                  _buildQuickFilterChip(
                    context: context,
                    ref: ref,
                    colorScheme: colorScheme,
                    label: 'Tất cả',
                    onTap: () {
                      ref.read(pointsHistoryFilterProvider.notifier).clearFilter();
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDateField({
    required BuildContext context,
    required ColorScheme colorScheme,
    required String label,
    required DateTime? value,
    required DateFormat dateFormatter,
    required VoidCallback onTap,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: colorScheme.onSurfaceVariant,
          ),
        ),
        const SizedBox(height: 4),
        InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(8),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
            decoration: BoxDecoration(
              color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  value != null ? dateFormatter.format(value) : 'Chọn',
                  style: TextStyle(
                    fontSize: 14,
                    color: value != null ? colorScheme.onSurface : colorScheme.onSurfaceVariant,
                  ),
                ),
                FaIcon(
                  FontAwesomeIcons.calendar,
                  size: 14,
                  color: colorScheme.onSurfaceVariant,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildQuickFilterChip({
    required BuildContext context,
    required WidgetRef ref,
    required ColorScheme colorScheme,
    required String label,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(16),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: colorScheme.outlineVariant),
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: colorScheme.onSurface,
          ),
        ),
      ),
    );
  }

  /// Build transaction card with new design
  Widget _buildTransactionCard(
    BuildContext context,
    LoyaltyPointEntryModel entry,
    ColorScheme colorScheme,
  ) {
    final dateFormatter = DateFormat('dd/MM/yyyy');

    // Determine points color
    Color pointsColor;
    String pointsPrefix;
    if (entry.points > 0) {
      pointsColor = AppColors.success;
      pointsPrefix = '+';
    } else if (entry.points < 0) {
      pointsColor = AppColors.danger;
      pointsPrefix = '';
    } else {
      pointsColor = colorScheme.onSurfaceVariant;
      pointsPrefix = '';
    }

    return Card(
      elevation: 1,
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      clipBehavior: Clip.antiAlias,
      child: Column(
        children: [
          // Header: Code and Date
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
              border: Border(
                bottom: BorderSide(
                  color: colorScheme.outlineVariant,
                  width: 1,
                ),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  entry.entryId,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w700,
                    color: colorScheme.primary,
                  ),
                ),
                Text(
                  dateFormatter.format(entry.timestamp),
                  style: TextStyle(
                    fontSize: 12,
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
              ],
            ),
          ),

          // Content: Description and Points
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // Description
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        entry.description,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: colorScheme.onSurface,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'Mã tham chiếu: #${entry.entryId}',
                        style: TextStyle(
                          fontSize: 13,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ),
                    ],
                  ),
                ),

                const SizedBox(width: 16),

                // Points
                Text(
                  '$pointsPrefix${entry.points} điểm',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w700,
                    color: pointsColor,
                  ),
                ),
              ],
            ),
          ),

          // Footer: Balance After
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            decoration: BoxDecoration(
              color: colorScheme.surfaceContainerLowest,
              border: Border(
                top: BorderSide(
                  color: colorScheme.outlineVariant.withValues(alpha: 0.5),
                  width: 1,
                ),
              ),
            ),
            child: Row(
              children: [
                Text(
                  'Số dư sau: ',
                  style: TextStyle(
                    fontSize: 13,
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
                Text(
                  '${entry.balanceAfter} điểm',
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.primary,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// Build inline empty state (inside scrollable list)
  Widget _buildEmptyStateInline(ColorScheme colorScheme) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 60),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FaIcon(
            FontAwesomeIcons.clockRotateLeft,
            size: 64,
            color: colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
          ),
          const SizedBox(height: 16),
          Text(
            'Không có giao dịch',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurfaceVariant,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            'Không tìm thấy giao dịch trong khoảng thời gian này',
            style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  /// Build error state
  Widget _buildErrorState(Object error, ColorScheme colorScheme) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FaIcon(
            FontAwesomeIcons.circleExclamation,
            size: 80,
            color: AppColors.danger.withValues(alpha: 0.7),
          ),
          const SizedBox(height: 16),
          Text(
            'Có lỗi xảy ra',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            error.toString(),
            style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}
