/// Page: Orders Page
///
/// Displays list of orders with search and filter functionality.
library;

import 'package:flutter/material.dart';
import 'package:worker/core/widgets/loading_indicator.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:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/orders/presentation/providers/orders_provider.dart';
import 'package:worker/features/orders/presentation/widgets/order_card.dart';

/// Orders Page
///
/// Features:
/// - Search bar for order numbers
/// - Filter pills for order status
/// - List of order cards
/// - Pull-to-refresh
class OrdersPage extends ConsumerStatefulWidget {
  const OrdersPage({super.key});

  @override
  ConsumerState<OrdersPage> createState() => _OrdersPageState();
}

class _OrdersPageState extends ConsumerState<OrdersPage> {
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _searchController.addListener(_onSearchChanged);
  }

  @override
  void dispose() {
    _searchController..removeListener(_onSearchChanged)
    ..dispose();
    super.dispose();
  }

  void _onSearchChanged() {
    ref
        .read(orderSearchQueryProvider.notifier)
        .updateQuery(_searchController.text);
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final ordersAsync = ref.watch(ordersProvider);
    final selectedStatus = ref.watch(selectedOrderStatusProvider);
    final searchQuery = ref.watch(orderSearchQueryProvider);

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        leading: IconButton(
          icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Danh sách đơn hàng',
          style: TextStyle(color: colorScheme.onSurface),
        ),
        elevation: AppBarSpecs.elevation,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
        actions: const [SizedBox(width: AppSpacing.sm)],
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          await ref.read(ordersProvider.notifier).refresh();
        },
        child: CustomScrollView(
          slivers: [
            // Sticky Search Bar
            SliverPersistentHeader(
              pinned: true,
              delegate: _SearchBarDelegate(
                child: Container(
                  color: colorScheme.surfaceContainerLowest,
                  padding: const EdgeInsets.all(16),
                  child: _buildSearchBar(colorScheme),
                ),
              ),
            ),

            // Sticky Filter Pills
            SliverPersistentHeader(
              pinned: true,
              delegate: _FilterPillsDelegate(
                child: Container(
                  color: colorScheme.surfaceContainerLowest,
                  child: _buildFilterPills(selectedStatus, colorScheme),
                ),
              ),
            ),

            // Orders List
            SliverPadding(
              padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
              sliver: ordersAsync.when(
                data: (orders) {
                  // Filter by status
                  var filtered = orders;
                  if (selectedStatus != null) {
                    filtered = filtered
                        .where((order) => order.status == selectedStatus)
                        .toList();
                  }

                  // Filter by search query
                  if (searchQuery.isNotEmpty) {
                    filtered = filtered
                        .where((order) => order.name
                            .toLowerCase()
                            .contains(searchQuery.toLowerCase()))
                        .toList();
                  }

                  // Sort by transaction date (newest first)
                  filtered.sort((a, b) {
                    try {
                      final aDate = DateTime.parse(a.transactionDate);
                      final bDate = DateTime.parse(b.transactionDate);
                      return bDate.compareTo(aDate);
                    } catch (e) {
                      return 0;
                    }
                  });

                  if (filtered.isEmpty) {
                    return _buildEmptyState(colorScheme);
                  }
                  return SliverList(
                    delegate: SliverChildBuilderDelegate((context, index) {
                      final order = filtered[index];
                      return OrderCard(
                        order: order,
                        onTap: () {
                          context.push('/orders/${order.name}');
                        },
                      );
                    }, childCount: filtered.length),
                  );
                },
                loading: () => _buildLoadingState(),
                error: (error, stack) => _buildErrorState(error, colorScheme),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Build search bar
  Widget _buildSearchBar(ColorScheme colorScheme) {
    return Container(
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: colorScheme.onSurface.withValues(alpha: 0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: TextField(
        controller: _searchController,
        decoration: InputDecoration(
          hintText: 'Mã đơn hàng',
          hintStyle: TextStyle(color: colorScheme.onSurfaceVariant, fontSize: 14),
          prefixIcon: Padding(
            padding: const EdgeInsets.all(14),
            child: FaIcon(
              FontAwesomeIcons.magnifyingGlass,
              color: colorScheme.onSurfaceVariant,
              size: 18,
            ),
          ),
          suffixIcon: _searchController.text.isNotEmpty
              ? IconButton(
                  icon: FaIcon(
                    FontAwesomeIcons.xmark,
                    color: colorScheme.onSurfaceVariant,
                    size: 18,
                  ),
                  onPressed: () {
                    _searchController.clear();
                  },
                )
              : null,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide.none,
          ),
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 16,
            vertical: 12,
          ),
        ),
      ),
    );
  }

  /// Build filter pills (dynamically from cached status list)
  Widget _buildFilterPills(String? selectedStatus, ColorScheme colorScheme) {
    final statusListAsync = ref.watch(orderStatusListProvider);

    return SizedBox(
      height: 48,
      child: statusListAsync.when(
        data: (statusList) {
          return ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            scrollDirection: Axis.horizontal,
            children: [
              // All filter (always first)
              _buildFilterChip(
                label: 'Tất cả',
                isSelected: selectedStatus == null,
                onTap: () {
                  ref.read(selectedOrderStatusProvider.notifier).clearSelection();
                },
                colorScheme: colorScheme,
              ),
              const SizedBox(width: 8),

              // Dynamic status filters from API
              ...statusList.map((status) {
                return Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: _buildFilterChip(
                    label: status.label,
                    isSelected: selectedStatus == status.label,
                    onTap: () {
                      ref
                          .read(selectedOrderStatusProvider.notifier)
                          .selectStatus(status.label);
                    },
                    colorScheme: colorScheme,
                  ),
                );
              }),
            ],
          );
        },
        loading: () {
          // Show minimal loading state or fallback to "All" only
          return ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            scrollDirection: Axis.horizontal,
            children: [
              _buildFilterChip(
                label: 'Tất cả',
                isSelected: true,
                onTap: () {},
                colorScheme: colorScheme,
              ),
            ],
          );
        },
        error: (error, stack) {
          // Show "All" filter only on error
          return ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            scrollDirection: Axis.horizontal,
            children: [
              _buildFilterChip(
                label: 'Tất cả',
                isSelected: true,
                onTap: () {},
                colorScheme: colorScheme,
              ),
            ],
          );
        },
      ),
    );
  }

  /// Build individual filter chip
  Widget _buildFilterChip({
    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.receipt,
              size: 80,
              color: colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
            ),
            const SizedBox(height: 16),
            Text(
              'Không có đơn hàng nào',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: colorScheme.onSurfaceVariant,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              'Thử tìm kiếm với từ khóa khác',
              style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
            ),
          ],
        ),
      ),
    );
  }

  /// Build loading state
  Widget _buildLoadingState() {
    return const SliverFillRemaining(
      child: const CustomLoadingIndicator(),
    );
  }

  /// Build error state
  Widget _buildErrorState(Object error, ColorScheme colorScheme) {
    return SliverFillRemaining(
      child: 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,
            ),
          ],
        ),
      ),
    );
  }
}

/// Search Bar Delegate for SliverPersistentHeader
class _SearchBarDelegate extends SliverPersistentHeaderDelegate {
  _SearchBarDelegate({required this.child});

  final Widget child;

  @override
  double get minExtent => 80; // Height when pinned

  @override
  double get maxExtent => 80; // Height when expanded

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return child;
  }

  @override
  bool shouldRebuild(_SearchBarDelegate oldDelegate) {
    return child != oldDelegate.child;
  }
}

/// Filter Pills Delegate for SliverPersistentHeader
class _FilterPillsDelegate extends SliverPersistentHeaderDelegate {
  _FilterPillsDelegate({required this.child});

  final Widget child;

  @override
  double get minExtent => 48; // Height when pinned (matches Container height)

  @override
  double get maxExtent => 48; // Height when expanded (matches Container height)

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return child;
  }

  @override
  bool shouldRebuild(_FilterPillsDelegate oldDelegate) {
    return child != oldDelegate.child;
  }
}
