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_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_popup_menu.dart';
import 'package:krow/features/profile/schedule/domain/bloc/schedule_bloc.dart';

class CalendarDataDetailSettingWidget extends StatefulWidget {
  const CalendarDataDetailSettingWidget({
    super.key,
    required this.selectedDate,
  });

  final DateTime? selectedDate;

  @override
  State<CalendarDataDetailSettingWidget> createState() =>
      _CalendarDataDetailSettingWidgetState();
}

class _CalendarDataDetailSettingWidgetState
    extends State<CalendarDataDetailSettingWidget> {
  var mode = SelectionMode.empty;

  @override
  Widget build(BuildContext context) {
    final selectedDate = widget.selectedDate;
    if (selectedDate == null) return const SizedBox.shrink();

    return Container(
      padding: const EdgeInsets.all(12),
      decoration: const BoxDecoration(
        color: AppColors.graySecondaryFrame,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(12),
          bottomRight: Radius.circular(12),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
           Text(
            'selected_date_details'.tr(),
            style: AppTextStyles.bodyMediumMed,
          ),
          const Divider(
            color: AppColors.grayTintStroke,
          ),
          Row(
            children: [
              Expanded(
                child: Text(
                  DateFormat('EEEE, MMMM d', context.locale.languageCode).format(selectedDate),
                  overflow: TextOverflow.ellipsis,
                  style: AppTextStyles.headingH3,
                ),
              ),
              const Gap(8),
              _buildKwPopupMenu(context, selectedDate),
            ],
          ),
          const Gap(16),
          Row(
            children: [
              Expanded(
                child: KwButton.outlinedPrimary(
                  label: 'cancel'.tr(),
                  onPressed: () {
                    context.read<ScheduleBloc>().add(
                          const ScheduleEventChangeMode(
                            isInScheduleAddMode: false,
                          ),
                        );
                  },
                ),
              ),
              const Gap(8),
              Expanded(
                child: KwButton.primary(
                  disabled: mode == SelectionMode.empty,
                  label: 'choose_time'.tr(),
                  onPressed: () {
                    BlocProvider.of<ScheduleBloc>(context).add(
                      ScheduleEventChangeMode(
                        isInEditScheduleMode: true,
                        isWeekly: mode == SelectionMode.weekly,
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  KwPopupMenu _buildKwPopupMenu(BuildContext context, DateTime selectedDate) {
    return KwPopupMenu(
      customButtonBuilder: (_, isOpened) {
        return _buildPopupButton(isOpened, selectedDate);
      },
      menuItems: [
        KwPopupMenuItem(
          icon: Assets.images.icons.calendarV2.svg(
            height: 16,
            width: 16,
          ),
          title: 'date'.tr(),
          onTap: () {
            setState(() {
              mode = SelectionMode.single;
            });
          },
        ),
        KwPopupMenuItem(
          icon: Assets.images.icons.calendar.svg(
            height: 16,
            width: 16,
          ),
          title: '${'all'.tr()} ${DateFormat('EEEE', context.locale.languageCode).format(selectedDate)}',
          onTap: () {
            setState(() {
              mode = SelectionMode.weekly;
            });
          },
        )
      ],
    );
  }

  Widget _buildPopupButton(bool isOpened, DateTime selectedDate) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      height: 34,
      padding: const EdgeInsets.only(left: 12, right: 10),
      decoration: BoxDecoration(
        color: AppColors.grayWhite,
        borderRadius: BorderRadius.circular(17),
        border: Border.all(
          color: isOpened ? AppColors.bgColorDark : AppColors.grayTintStroke,
          width: 1,
        ),
      ),
      child: Row(
        children: [
          if (mode == SelectionMode.empty)
             Text(
              'modify'.tr(),
              style: AppTextStyles.bodySmallMed,
            )
          else
            RichText(
              text: TextSpan(
                children: [
                  TextSpan(
                    text: '${'modify'.tr()}: ',
                    style: AppTextStyles.bodyMediumMed.copyWith(
                      color: AppColors.blackGray,
                    ),
                  ),
                  TextSpan(
                    text: '${mode == SelectionMode.single ? 'one'.tr() : 'all'.tr()} '
                        '${DateFormat('EEEE', context.locale.languageCode).format(selectedDate)}',
                    style: AppTextStyles.bodyMediumMed,
                  ),
                ],
              ),
            ),
          const Gap(4),
          AnimatedRotation(
            duration: const Duration(milliseconds: 150),
            turns: isOpened ? -0.5 : 0,
            child: Assets.images.icons.caretDown.svg(
              height: 16,
              width: 16,
            ),
          )
        ],
      ),
    );
  }
}

enum SelectionMode {empty, single, weekly}
