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 'package:krow_core/core.dart';
import 'package:krow_domain/krow_domain.dart';
import '../blocs/view_orders_cubit.dart';
import '../blocs/view_orders_state.dart';
import 'view_orders_filter_tab.dart';

/// The sticky header section for the View Orders page.
///
/// This widget contains:
/// - Top bar with title and post button
/// - Filter tabs (Up Next, Active, Completed)
/// - Calendar navigation controls
/// - Horizontal calendar grid
class ViewOrdersHeader extends StatelessWidget {
  /// Creates a [ViewOrdersHeader].
  const ViewOrdersHeader({
    required this.state,
    required this.calendarDays,
    super.key,
  });

  /// The current state of the view orders feature.
  final ViewOrdersState state;

  /// The list of calendar days to display.
  final List<DateTime> calendarDays;

  @override
  Widget build(BuildContext context) {
    return ClipRect(
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
        child: Container(
          decoration: BoxDecoration(
            color: UiColors.white.withValues(alpha: 0.8), // White with 0.8 alpha
            border: const 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,
                      ),
                    ),
                    if (state.filteredOrders.isNotEmpty)
                      UiButton.primary(
                        text: t.client_view_orders.post_button,
                        leadingIcon: UiIcons.add,
                        onPressed: () => Modular.to.toCreateOrder(),
                        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>[
                    ViewOrdersFilterTab(
                      label: t.client_view_orders.tabs.up_next,
                      isSelected: state.filterTab == 'all',
                      tabId: 'all',
                      count: state.upNextCount,
                    ),
                    const SizedBox(width: UiConstants.space6),
                    ViewOrdersFilterTab(
                      label: t.client_view_orders.tabs.active,
                      isSelected: state.filterTab == 'active',
                      tabId: 'active',
                      count: state.activeCount,
                    ),
                    const SizedBox(width: UiConstants.space6),
                    ViewOrdersFilterTab(
                      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: UiConstants.iconMd,
                        color: UiColors.iconSecondary,
                      ),
                      onPressed: () => BlocProvider.of<ViewOrdersCubit>(
                        context,
                      ).updateWeekOffset(-1),
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                      splashRadius: UiConstants.iconMd,
                    ),
                    Text(
                      DateFormat('MMMM yyyy').format(calendarDays.first),
                      style: UiTypography.body2m.copyWith(
                        color: UiColors.textSecondary,
                      ),
                    ),
                    IconButton(
                      icon: const Icon(
                        UiIcons.chevronRight,
                        size: UiConstants.iconMd,
                        color: UiColors.iconSecondary,
                      ),
                      onPressed: () => BlocProvider.of<ViewOrdersCubit>(
                        context,
                      ).updateWeekOffset(1),
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                      splashRadius: UiConstants.iconMd,
                    ),
                  ],
                ),
              ),

              // Calendar Grid
              SizedBox(
                height: UiConstants.space14 + UiConstants.space4,
                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,
                    );

                    // Check if date is in the past
                    final DateTime now = DateTime.now();
                    final DateTime today = DateTime(now.year, now.month, now.day);
                    final DateTime checkDate = DateTime(date.year, date.month, date.day);
                    final bool isPast = checkDate.isBefore(today);

                    return Opacity(
                      opacity: isPast && !isSelected ? 0.5 : 1.0,
                      child: GestureDetector(
                        onTap: () => BlocProvider.of<ViewOrdersCubit>(
                          context,
                        ).selectDate(date),
                        child: AnimatedContainer(
                          duration: const Duration(milliseconds: 200),
                          width: UiConstants.space12,
                          decoration: BoxDecoration(
                            color: isSelected ? UiColors.primary : UiColors.white,
                            borderRadius: UiConstants.radiusLg,
                            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, UiConstants.space1),
                                    ),
                                  ]
                                : null,
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Text(
                                DateFormat('dd').format(date),
                                style: UiTypography.title1m.copyWith(
                                  fontWeight: FontWeight.bold,
                                  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: UiConstants.space1 + 2,
                                  height: UiConstants.space1 + 2,
                                  decoration: BoxDecoration(
                                    color: isSelected
                                        ? UiColors.white
                                        : UiColors.primary,
                                    shape: BoxShape.circle,
                                  ),
                                ),
                              ],
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ),
              const SizedBox(height: UiConstants.space4),
            ],
          ),
        ),
      ),
    );
  }
}
