import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/application/common/int_extensions.dart';
import 'package:krow/core/entity/role_schedule_entity.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/kw_time_slot.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/features/create_event/presentation/role_schedule_dialog/bloc/role_schedule_dialog_bloc.dart';

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

  @override
  State<RecurringScheduleDialog> createState() =>
      _RecurringScheduleDialogState();

  static Future<List<RoleScheduleEntity>?> show(
      BuildContext context, List<RoleScheduleEntity>? schedule) {
    return showDialog(
      context: context,
      builder: (BuildContext dialogContext) {
        return BlocProvider(
          create: (context) => RoleScheduleDialogBloc(schedule ?? []),
          child: const RecurringScheduleDialog(),
        );
      },
    );
  }
}

class _RecurringScheduleDialogState extends State<RecurringScheduleDialog> {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RoleScheduleDialogBloc, RoleScheduleDialogState>(
      builder: (context, state) {
        return Center(
          child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            padding: const EdgeInsets.symmetric(vertical: 24),
            decoration: KwBoxDecorations.white24,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildHeader(context),
                const Gap(24),
                _buildDayTabs(state.schedule),
                const Gap(24),
                ...state.schedule.map((e) => _buildTimeSlots(e)),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 24),
                  child: KwButton.primary(
                    label: 'Save Slots',
                    onPressed: () {
                      Navigator.of(context).pop(state.schedule);
                    },
                  ),
                ),
                const Gap(8),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 24),
                  child: KwButton.outlinedPrimary(
                    label: 'Cancel',
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                'Event Schedule',
                style: AppTextStyles.bodyLargeMed,
              ),
              GestureDetector(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Assets.images.icons.x.svg(),
              ),
            ],
          ),
          const Gap(8),
          Padding(
            padding: const EdgeInsets.only(right: 24),
            child: Text(
              'Select the days and time slots that you want this schedule to recur on',
              style: AppTextStyles.bodySmallReg
                  .copyWith(color: AppColors.blackGray),
            ),
          )
        ],
      ),
    );
  }

  _buildDayTabs(List<RoleScheduleEntity> schedule) {
    return SingleChildScrollView(
      padding: const EdgeInsets.only(left: 24, right: 20),
      scrollDirection: Axis.horizontal,
      child: Row(
          children: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
              .indexed
              .map((e) {
        var (index, item) = e;
        var selected = schedule.any((element) => element.dayIndex == index);
        return GestureDetector(
          onTap: () {
            BlocProvider.of<RoleScheduleDialogBloc>(context)
                .add(TapOnScheduleDayEvent(index));
          },
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 150),
            margin: const EdgeInsets.only(right: 4),
            height: 46,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(23),
              color: selected ? AppColors.bgColorDark : Colors.transparent,
              border: Border.all(
                color: selected ? AppColors.bgColorDark : AppColors.grayStroke,
              ),
            ),
            child: Center(
                child: Text(
              item,
              style: AppTextStyles.bodyMediumReg.copyWith(
                  color: selected ? AppColors.grayWhite : AppColors.blackGray),
            )),
          ),
        );
      }).toList()),
    );
  }

  Widget _buildTimeSlots(RoleScheduleEntity e) {
    return Padding(
      padding: const EdgeInsets.only(left: 24, right: 24, bottom: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          RichText(
            text: TextSpan(
              text: e.dayIndex.getWeekdayId(),
              style: AppTextStyles.bodyMediumReg.copyWith(height: 1),
              children: [
                TextSpan(
                  text: ' Time Slot',
                  style: AppTextStyles.bodyTinyReg
                      .copyWith(color: AppColors.blackGray, height: 1),
                )
              ],
            ),
          ),
          const Gap(8),
          _timeRow(context, e),
          buildScheduleButton(),
        ],
      ),
    );
  }

  _timeRow(context, RoleScheduleEntity entity) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
          child: KwTimeSlotInput(
            key: ValueKey('dialog_start_time_key_${entity.dayIndex}'),
            label: 'Start Time',
            initialValue: entity.startTime,
            onChange: (value) {
              BlocProvider.of<RoleScheduleDialogBloc>(context)
                  .add(SetRoleScheduleStartTimeEvent(entity, value));
            },
          ),
        ),
        const Gap(8),
        Expanded(
          child: KwTimeSlotInput(
            key: ValueKey('dialog_start_time_key_${entity.dayIndex}'),
            label: 'End Time',
            initialValue: entity.endTime,
            onChange: (value) {
              BlocProvider.of<RoleScheduleDialogBloc>(context)
                  .add(SetRoleScheduleEndTimeEvent(entity, value));
            },
          ),
        ),
      ],
    );
  }

  GestureDetector buildScheduleButton() {
    return GestureDetector(
      onTap: () {},
      child: Container(
        margin: const EdgeInsets.only(top: 12),
        height: 20,
        child: Row(
          children: [
            Assets.images.icons.copy.svg(),
            const Gap(8),
            Text(
              'Copy Time to All',
              style: AppTextStyles.bodyMediumMed
                  .copyWith(color: AppColors.primaryBlue),
            ),
          ],
        ),
      ),
    );
  }
}
