/// Rewards Page
///
/// Displays gift catalog where users can redeem rewards with loyalty points.
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/features/loyalty/domain/entities/gift_catalog.dart';
import 'package:worker/features/loyalty/presentation/providers/gifts_provider.dart';
import 'package:worker/features/loyalty/presentation/providers/loyalty_points_provider.dart';
import 'package:worker/features/loyalty/presentation/widgets/points_balance_card.dart';
import 'package:worker/features/loyalty/presentation/widgets/reward_card.dart';
import 'package:worker/core/services/analytics_service.dart';

/// Rewards Page
///
/// Features:
/// - Points balance card with gradient
/// - Category filter pills
/// - Gift catalog grid (2 columns)
/// - Redemption functionality
class RewardsPage extends ConsumerWidget {
  const RewardsPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;
    final filteredGifts = ref.watch(filteredGiftsProvider);
    final selectedCategory = ref.watch(selectedGiftCategoryProvider);

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        leading: IconButton(
          icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Đổi quà tặng',
          style: TextStyle(color: colorScheme.onSurface),
        ),
        elevation: AppBarSpecs.elevation,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
        actions: [
          IconButton(
            icon: FaIcon(FontAwesomeIcons.circleInfo, color: colorScheme.onSurface, size: 20),
            onPressed: () => _showInfoDialog(context, colorScheme),
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          await ref.read(giftsProvider.notifier).refresh();
          await ref.read(loyaltyPointsProvider.notifier).refresh();
        },
        child: CustomScrollView(
          slivers: [
            // Points Balance Card
            const SliverToBoxAdapter(
              child: Padding(
                padding: EdgeInsets.all(16),
                child: PointsBalanceCard(),
              ),
            ),

            // Category Filter Pills
            SliverToBoxAdapter(
              child: _buildCategoryFilter(context, ref, selectedCategory, colorScheme),
            ),

            // Rewards Grid
            SliverPadding(
              padding: const EdgeInsets.fromLTRB(12, 8, 12, 24),
              sliver: filteredGifts.isEmpty
                  ? _buildEmptyState(colorScheme)
                  : SliverGrid(
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            childAspectRatio: 0.7,
                            crossAxisSpacing: 0,
                            mainAxisSpacing: 0,
                          ),
                      delegate: SliverChildBuilderDelegate((context, index) {
                        final gift = filteredGifts[index];
                        return RewardCard(
                          gift: gift,
                          onRedeem: () => _handleRedeemGift(context, ref, gift, colorScheme),
                        );
                      }, childCount: filteredGifts.length),
                    ),
            ),
          ],
        ),
      ),
    );
  }

  /// Show info dialog with usage instructions
  void _showInfoDialog(BuildContext context, ColorScheme colorScheme) {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text(
          'Hướng dẫn sử dụng',
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
        ),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                'Đây là nội dung hướng dẫn sử dụng cho tính năng Đổi quà tặng:',
                style: TextStyle(fontSize: 14),
              ),
              const SizedBox(height: 12),
              _buildInfoItem(
                'Sử dụng điểm tích lũy của bạn để đổi các phần quà giá trị trong danh mục.',
                colorScheme,
              ),
              _buildInfoItem(
                'Bấm vào một phần quà để xem chi tiết và điều kiện áp dụng.',
                colorScheme,
              ),
              _buildInfoItem(
                'Khi xác nhận đổi quà, bạn có thể chọn "Nhận hàng tại Showroom".',
                colorScheme,
              ),
              _buildInfoItem(
                'Nếu chọn "Nhận hàng tại Showroom", bạn sẽ cần chọn Showroom bạn muốn đến nhận từ danh sách thả xuống.',
                colorScheme,
              ),
              _buildInfoItem(
                'Quà đã đổi sẽ được chuyển vào mục "Quà của tôi" (trong trang Hội viên).',
                colorScheme,
              ),
            ],
          ),
        ),
        actions: [
          ElevatedButton(
            onPressed: () => Navigator.pop(context),
            style: ElevatedButton.styleFrom(
              backgroundColor: colorScheme.primary,
              foregroundColor: colorScheme.onPrimary,
              minimumSize: const Size(double.infinity, 44),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: const Text('Đóng'),
          ),
        ],
        actionsPadding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
        contentPadding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
        titlePadding: const EdgeInsets.fromLTRB(20, 20, 20, 8),
      ),
    );
  }

  /// Build info item with bullet point
  Widget _buildInfoItem(String text, ColorScheme colorScheme) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 6),
            child: FaIcon(FontAwesomeIcons.solidCircle, size: 6, color: colorScheme.onSurfaceVariant),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(text, style: const TextStyle(fontSize: 14, height: 1.5)),
          ),
        ],
      ),
    );
  }

  /// Build category filter pills
  Widget _buildCategoryFilter(
    BuildContext context,
    WidgetRef ref,
    GiftCategory? selectedCategory,
    ColorScheme colorScheme,
  ) {
    return Container(
      height: 48,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          // "Tất cả" (All) filter
          _buildFilterChip(
            context: context,
            ref: ref,
            label: 'Tất cả',
            isSelected: selectedCategory == null,
            onTap: () {
              ref.read(selectedGiftCategoryProvider.notifier).clearSelection();
            },
            colorScheme: colorScheme,
          ),
          const SizedBox(width: 8),

          // Voucher filter
          _buildFilterChip(
            context: context,
            ref: ref,
            label: 'Voucher',
            isSelected: selectedCategory == GiftCategory.voucher,
            onTap: () {
              ref
                  .read(selectedGiftCategoryProvider.notifier)
                  .setCategory(GiftCategory.voucher);
            },
            colorScheme: colorScheme,
          ),
          const SizedBox(width: 8),

          // Product filter
          _buildFilterChip(
            context: context,
            ref: ref,
            label: 'Sản phẩm',
            isSelected: selectedCategory == GiftCategory.product,
            onTap: () {
              ref
                  .read(selectedGiftCategoryProvider.notifier)
                  .setCategory(GiftCategory.product);
            },
            colorScheme: colorScheme,
          ),
          const SizedBox(width: 8),

          // Service filter
          _buildFilterChip(
            context: context,
            ref: ref,
            label: 'Dịch vụ',
            isSelected: selectedCategory == GiftCategory.service,
            onTap: () {
              ref
                  .read(selectedGiftCategoryProvider.notifier)
                  .setCategory(GiftCategory.service);
            },
            colorScheme: colorScheme,
          ),
          const SizedBox(width: 8),

          // Special offers filter
          _buildFilterChip(
            context: context,
            ref: ref,
            label: 'Ưu đãi đặc biệt',
            isSelected: selectedCategory == GiftCategory.discount,
            onTap: () {
              ref
                  .read(selectedGiftCategoryProvider.notifier)
                  .setCategory(GiftCategory.discount);
            },
            colorScheme: colorScheme,
          ),
        ],
      ),
    );
  }

  /// Build individual filter chip
  Widget _buildFilterChip({
    required BuildContext context,
    required WidgetRef ref,
    required String label,
    required bool isSelected,
    required VoidCallback onTap,
    required ColorScheme colorScheme,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? colorScheme.primary : colorScheme.surfaceContainerHighest,
          borderRadius: BorderRadius.circular(20),
        ),
        child: Center(
          child: Text(
            label,
            style: TextStyle(
              fontSize: 14,
              fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
              color: isSelected ? colorScheme.onPrimary : colorScheme.onSurface,
            ),
          ),
        ),
      ),
    );
  }

  /// Build empty state
  Widget _buildEmptyState(ColorScheme colorScheme) {
    return SliverFillRemaining(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FaIcon(
              FontAwesomeIcons.gift,
              size: 64,
              color: colorScheme.onSurfaceVariant,
            ),
            const SizedBox(height: 16),
            Text(
              'Không có quà tặng nào',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: colorScheme.onSurfaceVariant,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              'Vui lòng thử lại sau',
              style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
            ),
          ],
        ),
      ),
    );
  }

  /// Handle gift redemption
  void _handleRedeemGift(
    BuildContext context,
    WidgetRef ref,
    GiftCatalog gift,
    ColorScheme colorScheme,
  ) {
    final numberFormat = NumberFormat('#,###', 'vi_VN');
    final pointsState = ref.read(loyaltyPointsProvider);

    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Xác nhận đổi quà'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Bạn có chắc muốn đổi quà này?',
              style: TextStyle(fontSize: 14),
            ),
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: colorScheme.surfaceContainerLowest,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    gift.name,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text('Chi phí:', style: TextStyle(fontSize: 13)),
                      Text(
                        '${numberFormat.format(gift.pointsCost)} điểm',
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                          color: colorScheme.primary,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        'Số dư sau khi đổi:',
                        style: TextStyle(fontSize: 13),
                      ),
                      Text(
                        '${numberFormat.format(pointsState.availablePoints - gift.pointsCost)} điểm',
                        style: const TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Hủy'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _processRedemption(context, ref, gift);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: colorScheme.primary,
              foregroundColor: colorScheme.onPrimary,
            ),
            child: const Text('Xác nhận'),
          ),
        ],
      ),
    );
  }

  /// Process gift redemption
  void _processRedemption(
    BuildContext context,
    WidgetRef ref,
    GiftCatalog gift,
  ) {
    // Log spend points analytics event
    AnalyticsService.logSpendPoints(
      points: gift.pointsCost,
      itemName: gift.name,
    );

    // Deduct points
    ref.read(loyaltyPointsProvider.notifier).deductPoints(gift.pointsCost);

    // Show success message
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const FaIcon(FontAwesomeIcons.solidCircleCheck, color: Colors.white, size: 20),
            const SizedBox(width: 12),
            Expanded(child: Text('Đổi quà "${gift.name}" thành công!')),
          ],
        ),
        backgroundColor: AppColors.success,
        behavior: SnackBarBehavior.floating,
        duration: const Duration(seconds: 3),
      ),
    );

    // TODO: Navigate to gift code display page
    // context.push('/loyalty/my-gifts');
  }
}
