import 'dart:ui';
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 '../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 '../navigation/view_orders_navigator.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});

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

/// The internal view implementation for [ViewOrdersPage].
class ViewOrdersView extends StatelessWidget {
  /// Creates a [ViewOrdersView].
  const ViewOrdersView({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ViewOrdersCubit, ViewOrdersState>(
      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(
          backgroundColor: UiColors.white,
          body: Stack(
            children: <Widget>[
              // Background Gradient
              Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: <Color>[UiColors.bgSecondary, UiColors.white],
                    stops: <double>[0.0, 0.3],
                  ),
                ),
              ),

              SafeArea(
                child: Column(
                  children: <Widget>[
                    // Header + Filter + Calendar (Sticky behavior)
                    _buildHeader(
                      context: context,
                      state: state,
                      calendarDays: calendarDays,
                    ),

                    // Content List
                    Expanded(
                      child: 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 sticky header section.
  Widget _buildHeader({
    required BuildContext context,
    required ViewOrdersState state,
    required List<DateTime> calendarDays,
  }) {
    return ClipRect(
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
        child: Container(
          decoration: const BoxDecoration(
            color: Color(0xCCFFFFFF), // White with 0.8 alpha
            border: Border(
              bottom: BorderSide(color: UiColors.separatorSecondary),
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              // Top Bar
              Padding(
                padding: const EdgeInsets.fromLTRB(
                  UiConstants.space5,
                  UiConstants.space5,
                  UiConstants.space5,
                  UiConstants.space3,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      t.client_view_orders.title,
                      style: UiTypography.headline3m.copyWith(
                        color: UiColors.textPrimary,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    UiButton.primary(
                      text: t.client_view_orders.post_button,
                      leadingIcon: UiIcons.add,
                      onPressed: () => Modular.to.navigateToCreateOrder(),
                      size: UiButtonSize.small,
                      style: ElevatedButton.styleFrom(
                        minimumSize: const Size(0, 48),
                        maximumSize: const Size(0, 48),
                      ),
                    ),
                  ],
                ),
              ),

              // Filter Tabs
              Padding(
                padding: const EdgeInsets.only(bottom: UiConstants.space3),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    _buildFilterTab(
                      context,
                      label: t.client_view_orders.tabs.up_next,
                      isSelected: state.filterTab == 'all',
                      tabId: 'all',
                    ),
                    const SizedBox(width: UiConstants.space6),
                    _buildFilterTab(
                      context,
                      label: t.client_view_orders.tabs.active,
                      isSelected: state.filterTab == 'active',
                      tabId: 'active',
                      count: state.activeCount + state.upNextCount,
                    ),
                    const SizedBox(width: UiConstants.space6),
                    _buildFilterTab(
                      context,
                      label: t.client_view_orders.tabs.completed,
                      isSelected: state.filterTab == 'completed',
                      tabId: 'completed',
                      count: state.completedCount,
                    ),
                  ],
                ),
              ),

              // Calendar Header controls
              Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: UiConstants.space5,
                  vertical: UiConstants.space2,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    IconButton(
                      icon: const Icon(
                        UiIcons.chevronLeft,
                        size: 20,
                        color: UiColors.iconSecondary,
                      ),
                      onPressed: () => BlocProvider.of<ViewOrdersCubit>(
                        context,
                      ).updateWeekOffset(-1),
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                      splashRadius: 20,
                    ),
                    Text(
                      DateFormat('MMMM yyyy').format(calendarDays.first),
                      style: UiTypography.body2m.copyWith(
                        color: UiColors.textSecondary,
                      ),
                    ),
                    IconButton(
                      icon: const Icon(
                        UiIcons.chevronRight,
                        size: 20,
                        color: UiColors.iconSecondary,
                      ),
                      onPressed: () => BlocProvider.of<ViewOrdersCubit>(
                        context,
                      ).updateWeekOffset(1),
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                      splashRadius: 20,
                    ),
                  ],
                ),
              ),

              // Calendar Grid
              SizedBox(
                height: 72,
                child: ListView.separated(
                  padding: const EdgeInsets.symmetric(
                    horizontal: UiConstants.space5,
                  ),
                  scrollDirection: Axis.horizontal,
                  itemCount: 7,
                  separatorBuilder: (BuildContext context, int index) =>
                      const SizedBox(width: UiConstants.space2),
                  itemBuilder: (BuildContext context, int index) {
                    final DateTime date = calendarDays[index];
                    final bool isSelected =
                        state.selectedDate != null &&
                        date.year == state.selectedDate!.year &&
                        date.month == state.selectedDate!.month &&
                        date.day == state.selectedDate!.day;

                    // Check if this date has any shifts
                    final String dateStr = DateFormat(
                      'yyyy-MM-dd',
                    ).format(date);
                    final bool hasShifts = state.orders.any(
                      (OrderItem s) => s.date == dateStr,
                    );

                    return GestureDetector(
                      onTap: () => BlocProvider.of<ViewOrdersCubit>(
                        context,
                      ).selectDate(date),
                      child: AnimatedContainer(
                        duration: const Duration(milliseconds: 200),
                        width: 48,
                        decoration: BoxDecoration(
                          color: isSelected ? UiColors.primary : UiColors.white,
                          borderRadius: BorderRadius.circular(16),
                          border: Border.all(
                            color: isSelected
                                ? UiColors.primary
                                : UiColors.separatorPrimary,
                          ),
                          boxShadow: isSelected
                              ? <BoxShadow>[
                                  BoxShadow(
                                    color: UiColors.primary.withValues(
                                      alpha: 0.25,
                                    ),
                                    blurRadius: 12,
                                    offset: const Offset(0, 4),
                                  ),
                                ]
                              : null,
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              DateFormat('dd').format(date),
                              style: UiTypography.title2b.copyWith(
                                fontSize: 18,
                                color: isSelected
                                    ? UiColors.white
                                    : UiColors.textPrimary,
                              ),
                            ),
                            Text(
                              DateFormat('E').format(date),
                              style: UiTypography.footnote2m.copyWith(
                                color: isSelected
                                    ? UiColors.white.withValues(alpha: 0.8)
                                    : UiColors.textSecondary,
                              ),
                            ),
                            if (hasShifts) ...<Widget>[
                              const SizedBox(height: UiConstants.space1),
                              Container(
                                width: 6,
                                height: 6,
                                decoration: BoxDecoration(
                                  color: isSelected
                                      ? UiColors.white
                                      : UiColors.primary,
                                  shape: BoxShape.circle,
                                ),
                              ),
                            ],
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),
              const SizedBox(height: UiConstants.space4),
            ],
          ),
        ),
      ),
    );
  }

  /// Builds a single filter tab.
  Widget _buildFilterTab(
    BuildContext context, {
    required String label,
    required bool isSelected,
    required String tabId,
    int? count,
  }) {
    String text = label;
    if (count != null) {
      text = '$label ($count)';
    }

    return GestureDetector(
      onTap: () =>
          BlocProvider.of<ViewOrdersCubit>(context).selectFilterTab(tabId),
      child: Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(bottom: UiConstants.space2),
            child: Text(
              text,
              style: UiTypography.body2m.copyWith(
                color: isSelected ? UiColors.primary : UiColors.textSecondary,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          AnimatedContainer(
            duration: const Duration(milliseconds: 200),
            height: 2,
            width: isSelected ? 40 : 0,
            decoration: BoxDecoration(
              color: UiColors.primary,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          if (!isSelected) const SizedBox(height: 2),
        ],
      ),
    );
  }

  /// 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.navigateToCreateOrder(),
          ),
        ],
      ),
    );
  }

  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);
  }
}
