import 'package:core_localization/core_localization.dart';
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'
    hide ModularWatchExtension;
import 'package:intl/intl.dart';
import 'package:krow_domain/krow_domain.dart';

import '../blocs/availability_bloc.dart';
import '../blocs/availability_event.dart';
import '../blocs/availability_state.dart';

class AvailabilityPage extends StatefulWidget {
  const AvailabilityPage({super.key});

  @override
  State<AvailabilityPage> createState() => _AvailabilityPageState();
}

class _AvailabilityPageState extends State<AvailabilityPage> {
  final AvailabilityBloc _bloc = Modular.get<AvailabilityBloc>();

  @override
  void initState() {
    super.initState();
    _calculateInitialWeek();
  }

  void _calculateInitialWeek() {
    final today = DateTime.now();
    final day = today.weekday; // Mon=1, Sun=7
    final diff = day - 1; // Assuming Monday start
    DateTime currentWeekStart = today.subtract(Duration(days: diff));
    currentWeekStart = DateTime(
      currentWeekStart.year,
      currentWeekStart.month,
      currentWeekStart.day,
    );
    _bloc.add(LoadAvailability(currentWeekStart));
  }

  @override
  Widget build(BuildContext context) {
    final i18n = Translations.of(context).staff.availability;
    return BlocProvider.value(
      value: _bloc,
      child: Scaffold(
        appBar: UiAppBar(
          title: i18n.title,
          centerTitle: false,
          showBackButton: true,
        ),
        body: BlocListener<AvailabilityBloc, AvailabilityState>(
          listener: (context, state) {
            if (state is AvailabilityLoaded && state.successMessage != null) {
              UiSnackbar.show(
                context,
                message: state.successMessage!,
                type: UiSnackbarType.success,
              );
            }

            if (state is AvailabilityError) {
              UiSnackbar.show(
                context,
                message: translateErrorKey(state.message),
                type: UiSnackbarType.error,
              );
            }
          },
          child: BlocBuilder<AvailabilityBloc, AvailabilityState>(
            builder: (context, state) {
              if (state is AvailabilityLoading) {
                return const Center(child: CircularProgressIndicator());
              } else if (state is AvailabilityLoaded) {
                return Stack(
                  children: [
                    SingleChildScrollView(
                      padding: const EdgeInsets.only(bottom: 100),
                      child: Column(
                        children: [
                          Padding(
                            padding: const EdgeInsets.symmetric(
                              horizontal: UiConstants.space5,
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              spacing: UiConstants.space6,
                              children: [
                                _buildQuickSet(context),
                                _buildWeekNavigation(context, state),
                                _buildSelectedDayAvailability(
                                  context,
                                  state.selectedDayAvailability,
                                ),
                                _buildInfoCard(),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    if (state.isActionInProgress)
                      Positioned.fill(
                        child: Container(
                          color: UiColors.white.withValues(alpha: 0.5),
                          child: const Center(child: CircularProgressIndicator()),
                        ),
                      ),
                  ],
                );
              } else if (state is AvailabilityError) {
                return Center(
                  child: Padding(
                    padding: const EdgeInsets.all(24.0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          translateErrorKey(state.message),
                          textAlign: TextAlign.center,
                          style: UiTypography.body2r.textSecondary,
                        ),
                      ],
                    ),
                  ),
                );
              }
              return const SizedBox.shrink();
            },
          ),
        ),
      ),
    );
  }

  Widget _buildQuickSet(BuildContext context) {
    final i18n = Translations.of(context).staff.availability;
    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.primary.withValues(alpha: 0.1),
        borderRadius: UiConstants.radiusLg,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            i18n.quick_set_title,
            style: UiTypography.body2b,
          ),
          const SizedBox(height: UiConstants.space3),
          Row(
            children: [
              Expanded(
                child: _buildQuickSetButton(context, i18n.all_week, 'all'),
              ),
              const SizedBox(width: UiConstants.space2),
              Expanded(
                child: _buildQuickSetButton(context, i18n.weekdays, 'weekdays'),
              ),
              const SizedBox(width: UiConstants.space2),
              Expanded(
                child: _buildQuickSetButton(context, i18n.weekends, 'weekends'),
              ),
              const SizedBox(width: UiConstants.space2),
              Expanded(
                child: _buildQuickSetButton(
                  context,
                  i18n.clear_all,
                  'clear',
                  isDestructive: true,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildQuickSetButton(
    BuildContext context,
    String label,
    String type, {
    bool isDestructive = false,
  }) {
    return SizedBox(
      height: 32,
      child: OutlinedButton(
        onPressed: () =>
            context.read<AvailabilityBloc>().add(PerformQuickSet(type)),
        style: OutlinedButton.styleFrom(
          padding: EdgeInsets.zero,
          side: BorderSide(
            color: isDestructive
                ? UiColors.destructive.withValues(alpha: 0.2)
                : UiColors.primary.withValues(alpha: 0.2),
          ),
          backgroundColor: UiColors.transparent,
          shape: RoundedRectangleBorder(
            borderRadius: UiConstants.radiusLg,
          ),
          foregroundColor: isDestructive
              ? UiColors.destructive
              : UiColors.primary,
        ),
        child: Text(
          label,
          style: UiTypography.body4r,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ),
    );
  }

  Widget _buildWeekNavigation(BuildContext context, AvailabilityLoaded state) {
    // Middle date for month display
    final middleDate = state.currentWeekStart.add(const Duration(days: 3));
    final monthYear = DateFormat('MMMM yyyy').format(middleDate);

    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.cardViewBackground,
        borderRadius: UiConstants.radiusLg,
        border: Border.all(color: UiColors.border),
      ),
      child: Column(
        children: [
          // Nav Header
          Padding(
            padding: const EdgeInsets.only(bottom: UiConstants.space4),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildNavButton(
                  UiIcons.chevronLeft,
                  () => context.read<AvailabilityBloc>().add(
                    const NavigateWeek(-1),
                  ),
                ),
                Text(
                  monthYear,
                  style: UiTypography.title2b,
                ),
                _buildNavButton(
                  UiIcons.chevronRight,
                  () => context.read<AvailabilityBloc>().add(
                    const NavigateWeek(1),
                  ),
                ),
              ],
            ),
          ),
          // Days Row
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: state.days
                .map((day) => _buildDayItem(context, day, state.selectedDate))
                .toList(),
          ),
        ],
      ),
    );
  }

  Widget _buildNavButton(IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 32,
        height: 32,
        decoration: const BoxDecoration(
          color: UiColors.separatorSecondary,
          shape: BoxShape.circle,
        ),
        child: Icon(icon, size: 20, color: UiColors.iconSecondary),
      ),
    );
  }

  Widget _buildDayItem(
    BuildContext context,
    DayAvailability day,
    DateTime selectedDate,
  ) {
    final isSelected = AvailabilityLoaded.isSameDay(day.date, selectedDate);
    final isAvailable = day.isAvailable;
    final isToday = AvailabilityLoaded.isSameDay(day.date, DateTime.now());

    return Expanded(
      child: GestureDetector(
        onTap: () => context.read<AvailabilityBloc>().add(SelectDate(day.date)),
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 2),
          padding: const EdgeInsets.symmetric(vertical: UiConstants.space3),
          decoration: BoxDecoration(
            color: isSelected
                ? UiColors.primary
                : (isAvailable ? UiColors.tagSuccess : UiColors.bgSecondary),
            borderRadius: UiConstants.radiusLg,
            border: Border.all(
              color: isSelected
                  ? UiColors.primary
                  : (isAvailable
                      ? UiColors.success.withValues(alpha: 0.3)
                      : UiColors.transparent),
            ),
          ),
          child: Stack(
            clipBehavior: Clip.none,
            alignment: Alignment.center,
            children: [
              Column(
                children: [
                  Text(
                    day.date.day.toString().padLeft(2, '0'),
                    style: UiTypography.title1m.copyWith(
                      fontWeight: FontWeight.bold,
                      color: isSelected
                          ? UiColors.white
                          : (isAvailable
                              ? UiColors.textSuccess
                              : UiColors.textSecondary),
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    DateFormat('EEE').format(day.date),
                    style: UiTypography.footnote2r.copyWith(
                      color: isSelected
                          ? UiColors.white.withValues(alpha: 0.8)
                          : (isAvailable
                              ? UiColors.textSuccess
                              : UiColors.textSecondary),
                    ),
                  ),
                ],
              ),
              if (isToday && !isSelected)
                Positioned(
                  bottom: -8,
                  child: Container(
                    width: 6,
                    height: 6,
                    decoration: const BoxDecoration(
                      color: UiColors.primary,
                      shape: BoxShape.circle,
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSelectedDayAvailability(
    BuildContext context,
    DayAvailability day,
  ) {
    final dateStr = DateFormat('EEEE, MMM d').format(day.date);
    final isAvailable = day.isAvailable;

    return Container(
      padding: const EdgeInsets.all(UiConstants.space5),
      decoration: BoxDecoration(
        color: UiColors.cardViewBackground,
        borderRadius: UiConstants.radiusLg,
        border: Border.all(color: UiColors.border),
      ),
      child: Column(
        children: [
          // Header Row
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    dateStr,
                    style: UiTypography.title2b,
                  ),
                  Text(
                    isAvailable
                        ? Translations.of(context)
                            .staff
                            .availability
                            .available_status
                        : Translations.of(context)
                            .staff
                            .availability
                            .not_available_status,
                    style: UiTypography.body2r.textSecondary,
                  ),
                ],
              ),
              Switch(
                value: isAvailable,
                onChanged: (val) =>
                    context.read<AvailabilityBloc>().add(ToggleDayStatus(day)),
                activeColor: UiColors.primary,
              ),
            ],
          ),

          const SizedBox(height: UiConstants.space4),

          // Time Slots (only from Domain)
          ...day.slots.map((slot) {
            // Get UI config for this slot ID
            final uiConfig = _getSlotUiConfig(slot.id);

            return _buildTimeSlotItem(context, day, slot, uiConfig);
          }).toList(),
        ],
      ),
    );
  }

  Map<String, dynamic> _getSlotUiConfig(String slotId) {
    switch (slotId) {
      case 'morning':
        return {
          'icon': UiIcons.sunrise,
          'bg': UiColors.primary.withValues(alpha: 0.1),
          'iconColor': UiColors.primary,
        };
      case 'afternoon':
        return {
          'icon': UiIcons.sun,
          'bg': UiColors.primary.withValues(alpha: 0.2),
          'iconColor': UiColors.primary,
        };
      case 'evening':
        return {
          'icon': UiIcons.moon,
          'bg': UiColors.bgSecondary,
          'iconColor': UiColors.foreground,
        };
      default:
        return {
          'icon': UiIcons.clock,
          'bg': UiColors.bgSecondary,
          'iconColor': UiColors.iconSecondary,
        };
    }
  }

  Widget _buildTimeSlotItem(
    BuildContext context,
    DayAvailability day,
    AvailabilitySlot slot,
    Map<String, dynamic> uiConfig,
  ) {
    // Determine styles based on state
    final isEnabled = day.isAvailable;
    final isActive = slot.isAvailable;

    // Container style
    Color bgColor;
    Color borderColor;

    if (!isEnabled) {
      bgColor = UiColors.bgSecondary;
      borderColor = UiColors.borderInactive;
    } else if (isActive) {
      bgColor = UiColors.primary.withValues(alpha: 0.05);
      borderColor = UiColors.primary.withValues(alpha: 0.2);
    } else {
      bgColor = UiColors.bgSecondary;
      borderColor = UiColors.borderPrimary;
    }

    // Text colors
    final titleColor = (isEnabled && isActive)
        ? UiColors.foreground
        : UiColors.mutedForeground;
    final subtitleColor = (isEnabled && isActive)
        ? UiColors.mutedForeground
        : UiColors.textInactive;

    return GestureDetector(
      onTap: isEnabled
          ? () => context.read<AvailabilityBloc>().add(
              ToggleSlotStatus(day, slot.id),
            )
          : null,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        margin: const EdgeInsets.only(bottom: UiConstants.space3),
        padding: const EdgeInsets.all(UiConstants.space4),
        decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.circular(UiConstants.radiusBase),
          border: Border.all(color: borderColor, width: 2),
        ),
        child: Row(
          children: [
            // Icon
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: uiConfig['bg'],
                borderRadius: BorderRadius.circular(UiConstants.radiusBase),
              ),
              child: Icon(
                uiConfig['icon'],
                color: uiConfig['iconColor'],
                size: 20,
              ),
            ),
            const SizedBox(width: UiConstants.space3),
            // Text
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    slot.label,
                    style: UiTypography.body2m.copyWith(color: titleColor),
                  ),
                  Text(
                    slot.timeRange,
                    style: UiTypography.body3r.copyWith(color: subtitleColor),
                  ),
                ],
              ),
            ),
            // Checkbox indicator
            if (isEnabled && isActive)
              Container(
                width: 24,
                height: 24,
                decoration: const BoxDecoration(
                  color: UiColors.primary,
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  UiIcons.check,
                  size: 16,
                  color: UiColors.white,
                ),
              )
            else if (isEnabled && !isActive)
              Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: UiColors.borderStill,
                    width: 2,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoCard() {
    final i18n = Translations.of(context).staff.availability;
    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.primary.withValues(alpha: 0.05),
        borderRadius: BorderRadius.circular(UiConstants.radiusBase),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: UiConstants.space3,
        children: [
          const Icon(UiIcons.clock, size: 20, color: UiColors.primary),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              spacing: UiConstants.space1,
              children: [
                Text(
                  i18n.auto_match_title,
                  style: UiTypography.body2m,
                ),
                Text(
                  i18n.auto_match_description,
                  style: UiTypography.body3r.textSecondary,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
