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/data/models/event/event_model.dart';
import 'package:krow/core/entity/event_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/core/presentation/widgets/ui_kit/kw_dropdown.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_option_selector.dart';
import 'package:krow/features/create_event/domain/bloc/create_event_bloc.dart';
import 'package:krow/features/create_event/presentation/event_date_section/bloc/date_selector_bloc.dart';
import 'package:krow/features/create_event/presentation/event_date_section/create_event_date_popup.dart';

class EventDateInputWidget extends StatelessWidget {
  final EventEntity entity;

  const EventDateInputWidget(this.entity, {super.key});

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<DateSelectorBloc, DateSelectorState>(
      listener: (context, state) {
        BlocProvider.of<CreateEventBloc>(context)
            .add(CreateEventEntityUpdatedEvent());
      },
      builder: (context, state) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: state.recurringType == EventScheduleType.oneTime
              ? ([
                  _buildDateInput(context, 'Date', state.startDate, (newDate) {
                    BlocProvider.of<DateSelectorBloc>(context)
                        .add(DateSelectorEventChangeStartDate(newDate, entity));
                  }),
                ])
              : [
                  const Gap(16),
                  const Divider(
                    color: AppColors.grayTintStroke,
                    thickness: 1,
                    height: 0,
                  ),
                  _buildDateInput(context, 'Start Date', state.startDate,
                      (newDate) {
                    BlocProvider.of<DateSelectorBloc>(context)
                        .add(DateSelectorEventChangeStartDate(newDate, entity));
                  }),
                  ..._buildRepeatSelector(state, context),
                  ...buildEndTypeSelector(state, context),
                  AnimatedCrossFade(
                    firstChild: _buildDateInput(
                        context, 'End Date', state.endDate, (newDate) {
                      BlocProvider.of<DateSelectorBloc>(context)
                          .add(DateSelectorEventChangeEndDate(newDate, entity));
                    }),
                    secondChild: _buildEndAfterDropdown(state, context),
                    crossFadeState: state.endDateType == EndDateType.endDate
                        ? CrossFadeState.showFirst
                        : CrossFadeState.showSecond,
                    duration: const Duration(milliseconds: 200),
                  ),
                  const Gap(16),
                  const Divider(
                    color: AppColors.grayTintStroke,
                    thickness: 1,
                    height: 0,
                  ),
                  const Gap(8),
                ],
        );
      },
    );
  }

  Widget _buildEndAfterDropdown(DateSelectorState state, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: KwDropdown<int>(
        selectedItem: KwDropDownItem(
            data: state.andsAfterWeeksCount,
            title: '${state.andsAfterWeeksCount} Weeks'),
        hintText: '',
        title: 'After',
        horizontalPadding: 28,
        onSelected: (int item) {
          BlocProvider.of<DateSelectorBloc>(context)
              .add(DateSelectorEventChangeEndsAfterWeeks(item));
        },
        items: const [
          KwDropDownItem(data: 1, title: '1 Weeks'),
          KwDropDownItem(data: 2, title: '2 Weeks'),
          KwDropDownItem(data: 3, title: '3 Weeks'),
          KwDropDownItem(data: 5, title: '4 Weeks'),
        ],
      ),
    );
  }

  List<Widget> _buildRepeatSelector(
      DateSelectorState state, BuildContext context) {
    return [
      Padding(
        padding: const EdgeInsets.only(left: 16, top: 8, bottom: 4),
        child: Text(
          'Repeat',
          style: AppTextStyles.bodyTinyReg.copyWith(color: AppColors.blackGray),
        ),
      ),
      KwOptionSelector(
          selectedIndex: state.repeatType?.index,
          backgroundColor: AppColors.grayPrimaryFrame,
          onChanged: (index) {
            BlocProvider.of<DateSelectorBloc>(context).add(
                DateSelectorEventRepeatType(EventRepeatType.values[index]));
          },
          items: const [
            'Weekly',
            'Daily',
          ])
    ];
  }

  Widget _buildDateInput(BuildContext context, String title, DateTime? date,
      Function(DateTime date) onSelect) {
    var formattedDate = date == null
        ? 'mm.dd.yyyy'
        : DateFormat('MM.dd.yyyy').format(date).toLowerCase();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 16, top: 8),
          child: Text(
            'Date',
            style:
                AppTextStyles.bodyTinyReg.copyWith(color: AppColors.blackGray),
          ),
        ),
        const Gap(4),
        GestureDetector(
          onTap: () async {
            var newDate = await CreateEventDatePopup.show(
                context: context, initDate: date);
            if (newDate != null && context.mounted) {
              onSelect(newDate);
            }
          },
          child: Container(
            height: 48,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            decoration: BoxDecoration(
              border: Border.all(color: AppColors.grayStroke),
              borderRadius: BorderRadius.circular(24),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(formattedDate,
                    style: AppTextStyles.bodyMediumReg.copyWith(
                        color: date != null ? null : AppColors.blackGray)),
                const Gap(10),
                Assets.images.icons.calendar.svg(width: 16, height: 16),
              ],
            ),
          ),
        ),
      ],
    );
  }

  List<Widget> buildEndTypeSelector(
      DateSelectorState state, BuildContext context) {
    return [
      const Gap(24),
      KwOptionSelector(
          selectedIndex: state.endDateType?.index,
          onChanged: (index) {
            BlocProvider.of<DateSelectorBloc>(context)
                .add(DateSelectorEventEndType(EndDateType.values[index]));
          },
          height: 26,
          selectorHeight: 4,
          textStyle:
              AppTextStyles.bodyMediumReg.copyWith(color: AppColors.blackGray),
          selectedTextStyle: AppTextStyles.bodyMediumMed,
          itemAlign: Alignment.topCenter,
          items: const [
            'Ends on Date',
            'Ends After # Weeks',
          ])
    ];
  }
}
