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_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/features/create_event/presentation/create_role_section/bloc/create_role_bloc.dart';
import 'package:krow/features/create_event/presentation/role_schedule_dialog/recurring_schedule_dialog.dart';

class RecurringScheduleWidget extends StatelessWidget {
  const RecurringScheduleWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CreateRoleBloc, CreateRoleState>(
      builder: (context, state) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            if (state.entity.schedule != null &&
                (state.entity.schedule?.isNotEmpty ?? false)) ...[
              const Gap(12),
              Padding(
                padding: const EdgeInsets.only(left: 16.0),
                child: const Text(
                  'Schedule',
                  style: AppTextStyles.bodyMediumReg,
                ),
              ),
              ...state.entity.schedule!.map((e) => _buildScheduleItem(e)),
              const Gap(8),
            ],
            buildScheduleButton(context, state),
          ],
        );
      },
    );
  }

  GestureDetector buildScheduleButton(
      BuildContext context, CreateRoleState state) {
    return GestureDetector(
      onTap: () async {
        var result =
            await RecurringScheduleDialog.show(context, state.entity.schedule);
        if (result != null) {
          context
              .read<CreateRoleBloc>()
              .add(CreateRoleSetScheduleEvent(result));
        }
      },
      child: Container(
        margin: const EdgeInsets.only(top: 12),
        height: 20,
        child: Row(
          children: [
            Assets.images.icons.calendarEdit.svg(),
            const Gap(8),
            Text(
              'Set Work Days',
              style: AppTextStyles.bodyMediumMed
                  .copyWith(color: AppColors.primaryBlue),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildScheduleItem(RoleScheduleEntity e) {
    return Container(
      padding: const EdgeInsets.only(left: 16, right: 16),
      margin: const EdgeInsets.only(top: 8),
      height: 46,
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(23),
        border: Border.all(color: AppColors.grayStroke, width: 1),
      ),
      child: Text(e.dayIndex.getWeekdayId()),
    );
  }
}
