import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:intl/intl.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_box_decorations.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/ui_kit/dialogs/kw_dialog.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_popup_menu.dart';
import 'package:krow/features/profile/schedule/domain/entities/day_shedule.dart';
import 'package:krow/features/profile/schedule/domain/bloc/schedule_bloc.dart';
import 'package:krow/features/profile/schedule/domain/entities/schedule_slot.dart';
import 'package:krow/features/profile/schedule/presentation/widgets/shared_functions.dart';

import '../../../../../app.dart';

class CalendarSlotListWidget extends StatelessWidget {
  const CalendarSlotListWidget({
    super.key,
    required this.selectedSchedules,
  });

  final List<DaySchedule> selectedSchedules;

  static final timeFormat = DateFormat('h:mma', 'en');

  Future<void> _onDeleteButtonPress(
    BuildContext context,
    DaySchedule schedule,
  ) async {
    final scheduleBloc = context.read<ScheduleBloc>();
    if (!schedule.isWeekly) {
      scheduleBloc.add(
        ScheduleEventDeleteSchedule(schedule: schedule),
      );
      return;
    }

    await KwDialog.show(
      context: context,
      state: KwDialogState.warning,
      icon: Assets.images.icons.alertTriangle,
      title: 'delete_schedule'.tr(),
      message: 'delete_schedule_message'.tr(args: [(DateFormat('EEEE', context.locale.languageCode).format(schedule.date))]),
      primaryButtonLabel: 'confirm'.tr(),
      secondaryButtonLabel: 'cancel'.tr(),
      onPrimaryButtonPressed: (dialogContext) {
        scheduleBloc.add(
          ScheduleEventDeleteSchedule(schedule: schedule),
        );

        Navigator.of(dialogContext).pop();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ScheduleBloc, ScheduleState>(
      buildWhen: (previous, current) =>
          previous.selectedDates != current.selectedDates,
      builder: (context, state) {
        if (state.selectedDates.isEmpty) return const SizedBox.shrink();

        return Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Gap(12),
             Text(
              'slot_details'.tr(),
              style: AppTextStyles.bodySmallMed,
            ),
            const Gap(12),
            for (var schedule in selectedSchedules)
              _buildInfoWidget(context, schedule),
          ],
        );
      },
    );
  }

  Widget _buildInfoWidget(context, DaySchedule schedule) {
    return Container(
      margin: const EdgeInsets.only(top: 12),
      padding: const EdgeInsets.all(12),
      decoration: KwBoxDecorations.primaryLight8,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Container(
                height: 36,
                width: 36,
                decoration: BoxDecoration(
                  color: AppColors.grayWhite,
                  borderRadius: BorderRadius.circular(6),
                  border: Border.all(
                    color: AppColors.grayStroke,
                    width: 1,
                  ),
                ),
                child: Center(
                  child: Assets.images.icons.calendar.svg(),
                ),
              ),
              const Gap(12),
              Text(
                DateFormat('MMMM d', appContext!.locale.languageCode).format(schedule.date),
                style: AppTextStyles.headingH3,
              ),
              const Spacer(),
              KwPopupMenu(
                horizontalMargin: 24,
                menuItems: [
                  KwPopupMenuItem(
                    title: 'edit'.tr(),
                    icon: Assets.images.icons.edit.svg(),
                    onTap: () => onEditButtonPress(
                      context,
                      editedDate: schedule.date,
                      isWeeklySchedule: schedule.isWeekly,
                    ),
                  ),
                  KwPopupMenuItem(
                    title: 'delete'.tr(),
                    textStyle: AppTextStyles.bodyMediumReg.copyWith(
                      color: AppColors.statusError,
                    ),
                    icon: Assets.images.icons.trash.svg(),
                    onTap: () => _onDeleteButtonPress(context, schedule),
                  ),
                ],
              ),
            ],
          ),
          const Gap(12),
          Text(
            'time_slots'.tr(),
            style: AppTextStyles.bodySmallMed.copyWith(
              color: AppColors.blackGray,
            ),
          ),
          for (var i = 0; i < schedule.slots.length / 2; i++)
            Row(
              children: [
                _buildSlotWidget(context, schedule.slots[i * 2]),
                const Gap(12),
                schedule.slots.length > (i * 2 + 1)
                    ? _buildSlotWidget(context, schedule.slots[i * 2 + 1])
                    : const Spacer(),
              ],
            ),
        ],
      ),
    );
  }

  _buildSlotWidget(BuildContext context, ScheduleSlot slot) {
    return Expanded(
      child: Container(
        margin: const EdgeInsets.only(top: 12),
        height: 36,
        decoration: BoxDecoration(
          color: AppColors.grayWhite,
          borderRadius: BorderRadius.circular(6),
          border: Border.all(
            color: AppColors.grayTintStroke,
            width: 1,
          ),
        ),
        child: Center(
          child: Text(
            '${timeFormat.format(slot.startTime)} - '
            '${timeFormat.format(slot.endTime)}',
            style: AppTextStyles.bodyMediumReg,
          ),
        ),
      ),
    );
  }
}
