import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:intl/intl.dart';

import 'package:core_localization/core_localization.dart';
import 'package:krow_core/core.dart';
import '../blocs/view_orders_cubit.dart';
import '../blocs/view_orders_state.dart';
import 'package:krow_domain/krow_domain.dart';
import '../widgets/view_order_card.dart';
import '../widgets/view_orders_header.dart';

/// The main page for viewing client orders.
///
/// This page follows the KROW Clean Architecture by:
/// - Being a [StatelessWidget].
/// - Using [ViewOrdersCubit] for state management.
/// - Adhering to the project's Design System.
class ViewOrdersPage extends StatelessWidget {
  /// Creates a [ViewOrdersPage].
  const ViewOrdersPage({super.key, this.initialDate});

  /// The initial date to display orders for.
  final DateTime? initialDate;

  @override
  Widget build(BuildContext context) {
    return BlocProvider<ViewOrdersCubit>(
      create: (BuildContext context) => Modular.get<ViewOrdersCubit>(),
      child: ViewOrdersView(initialDate: initialDate),
    );
  }
}

/// The internal view implementation for [ViewOrdersPage].
class ViewOrdersView extends StatefulWidget {
  /// Creates a [ViewOrdersView].
  const ViewOrdersView({super.key, this.initialDate});
  
  /// The initial date to display orders for.
  final DateTime? initialDate;

  @override
  State<ViewOrdersView> createState() => _ViewOrdersViewState();
}

class _ViewOrdersViewState extends State<ViewOrdersView> {
  bool _didInitialJump = false;
  ViewOrdersCubit? _cubit;

  @override
  void initState() {
    super.initState();
    // Force initialization of cubit immediately
    _cubit = BlocProvider.of<ViewOrdersCubit>(context, listen: false);

    if (widget.initialDate != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) return;
        if (_didInitialJump) return;
        _didInitialJump = true;
        _cubit?.jumpToDate(widget.initialDate!);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<ViewOrdersCubit, ViewOrdersState>(
      listener: (BuildContext context, ViewOrdersState state) {
        if (state.status == ViewOrdersStatus.failure &&
            state.errorMessage != null) {
          UiSnackbar.show(
            context,
            message: translateErrorKey(state.errorMessage!),
            type: UiSnackbarType.error,
          );
        }
      },
      builder: (BuildContext context, ViewOrdersState state) {
        final List<DateTime> calendarDays = state.calendarDays;
        final List<OrderItem> filteredOrders = state.filteredOrders;

        // Header Colors logic from prototype
        String sectionTitle = '';
        Color dotColor = UiColors.transparent;

        if (state.filterTab == 'all') {
          sectionTitle = t.client_view_orders.tabs.up_next;
          dotColor = UiColors.primary;
        } else if (state.filterTab == 'active') {
          sectionTitle = t.client_view_orders.tabs.active;
          dotColor = UiColors.textWarning;
        } else if (state.filterTab == 'completed') {
          sectionTitle = t.client_view_orders.tabs.completed;
          dotColor =
              UiColors.primary; // Reverting to primary blue for consistency
        }

        return Scaffold(
          body: SafeArea(
            child: Column(
              children: <Widget>[
                // Header + Filter + Calendar (Sticky behavior)
                ViewOrdersHeader(
                  state: state,
                  calendarDays: calendarDays,
                ),
          
                // Content List
                Expanded(
                  child: state.status == ViewOrdersStatus.failure
                      ? _buildErrorState(context: context, state: state)
                      : filteredOrders.isEmpty
                          ? _buildEmptyState(context: context, state: state)
                          : ListView(
                              padding: const EdgeInsets.fromLTRB(
                                UiConstants.space5,
                                UiConstants.space4,
                                UiConstants.space5,
                                100,
                              ),
                              children: <Widget>[
                                if (filteredOrders.isNotEmpty)
                                  Padding(
                                    padding: const EdgeInsets.only(
                                      bottom: UiConstants.space3,
                                    ),
                                    child: Row(
                                      children: <Widget>[
                                        Container(
                                          width: 8,
                                          height: 8,
                                          decoration: BoxDecoration(
                                            color: dotColor,
                                            shape: BoxShape.circle,
                                          ),
                                        ),
                                        const SizedBox(
                                          width: UiConstants.space2,
                                        ),
                                        Text(
                                          sectionTitle.toUpperCase(),
                                          style: UiTypography.titleUppercase2m
                                              .copyWith(
                                                color: UiColors.textPrimary,
                                              ),
                                        ),
                                        const SizedBox(
                                          width: UiConstants.space1,
                                        ),
                                        Text(
                                          '(${filteredOrders.length})',
                                          style: UiTypography.footnote1r
                                              .copyWith(
                                                color: UiColors.textSecondary,
                                              ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ...filteredOrders.map(
                                  (OrderItem order) => Padding(
                                    padding: const EdgeInsets.only(
                                      bottom: UiConstants.space3,
                                    ),
                                    child: ViewOrderCard(order: order),
                                  ),
                                ),
                              ],
                            ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// Builds the empty state view.
  Widget _buildEmptyState({
    required BuildContext context,
    required ViewOrdersState state,
  }) {
    final String dateStr = state.selectedDate != null
        ? _formatDateHeader(state.selectedDate!)
        : 'this date';

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          const Icon(UiIcons.calendar, size: 48, color: UiColors.iconInactive),
          const SizedBox(height: UiConstants.space3),
          Text(
            t.client_view_orders.no_orders(date: dateStr),
            style: UiTypography.body2r.copyWith(color: UiColors.textSecondary),
          ),
          const SizedBox(height: UiConstants.space4),
          UiButton.primary(
            text: t.client_view_orders.post_order,
            leadingIcon: UiIcons.add,
            onPressed: () => Modular.to.toCreateOrder(),
          ),
        ],
      ),
    );
  }

  static String _formatDateHeader(DateTime date) {
    final DateTime now = DateTime.now();
    final DateTime today = DateTime(now.year, now.month, now.day);
    final DateTime tomorrow = today.add(const Duration(days: 1));
    final DateTime checkDate = DateTime(date.year, date.month, date.day);

    if (checkDate == today) return 'Today';
    if (checkDate == tomorrow) return 'Tomorrow';
    return DateFormat('EEE, MMM d').format(date);
  }

  Widget _buildErrorState({
    required BuildContext context,
    required ViewOrdersState state,
  }) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          const Icon(
            UiIcons.error,
            size: 48,
            color: UiColors.error,
          ),
          const SizedBox(height: UiConstants.space4),
          Text(
            state.errorMessage != null
                ? translateErrorKey(state.errorMessage!)
                : 'An error occurred',
            style: UiTypography.body1m.textError,
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: UiConstants.space4),
          UiButton.secondary(
            text: 'Retry',
            onPressed: () => BlocProvider.of<ViewOrdersCubit>(context)
                .jumpToDate(state.selectedDate ?? DateTime.now()),
          ),
        ],
      ),
    );
  }
}
