import 'package:auto_route/auto_route.dart';
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: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/scroll_layout_helper.dart';
import 'package:krow/core/presentation/widgets/ui_kit/check_box_card.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_app_bar.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/uploud_image_card.dart';
import 'package:krow/features/profile/role_kit/domain/bloc/role_kit_bloc.dart';
import 'package:krow/features/profile/role_kit/domain/bloc/role_kit_event.dart';
import 'package:krow/features/profile/role_kit/domain/bloc/role_kit_state.dart';
import 'package:krow/features/profile/role_kit/domain/role_kit_entity.dart';
import 'package:krow/features/profile/role_kit/domain/staff_role_kit_repository_impl.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

@RoutePage()
class RoleKitScreen extends StatelessWidget {
  const RoleKitScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<RoleKitBloc, RoleKitState>(
        listenWhen: (oldState, newState) =>
            oldState.success != newState.success ||
            oldState.apiError != newState.apiError,
        listener: (context, state) {
          if (state.success) {
            context.router.maybePop();
          }
          if (state.apiError != null) {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
              content: Text(state.apiError ?? ''),
            ));
          }
        },
        builder: (context, state) {
          return ModalProgressHUD(
            inAsyncCall: state.loading,
            child: Scaffold(
              appBar: KwAppBar(
                titleText: state.roleKitType == RoleKitType.uniform
                    ? '${state.selectedRole?.skill?.name} ${'uniform'.tr()}'
                    : '${state.selectedRole?.skill?.name} ${'equipment'.tr()}',
              ),
              body: ScrollLayoutHelper(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                upperWidget: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Text(
                      '${'please_indicate'.tr()} ${state.roleKitType == RoleKitType.uniform ? 'uniform'.tr().toLowerCase() : 'equipment'.tr().toLowerCase()}:',
                      style: AppTextStyles.bodyTinyReg
                          .copyWith(color: AppColors.blackGray),
                    ),
                    if (state.showError) _buildErrorMessage(),
                    const Gap(24),
                    if (state.roleKitItems
                        .where((item) => item.isMandatory)
                        .isNotEmpty) ...[
                      _buildSectionLabel('mandatory_items'.tr()),
                      _buildItems(
                          context, state.roleKitItems, true, state.showError),
                      const Gap(4),
                    ],
                    if (state.roleKitItems
                        .where((item) => !item.isMandatory)
                        .isNotEmpty) ...[
                      _buildSectionLabel('optional_items'.tr()),
                      _buildItems(
                          context, state.roleKitItems, false, state.showError),
                    ],
                    if (state.roleKitItems
                        .where((item) => item.needPhoto)
                        .isNotEmpty) ...[
                      const Gap(32),
                      _buildSectionLabel('confirm_availability'.tr()),
                      _buildUploadProofItems(
                          context, state.roleKitItems, state.showError),
                    ]
                  ],
                ),
                lowerWidget: KwButton.primary(
                    label: 'confirm'.tr(),
                    onPressed: () {
                      BlocProvider.of<RoleKitBloc>(context)
                          .add(RoleKitEventSubmit());
                    }),
              ),
            ),
          );
        });
  }

  Widget _buildSectionLabel(String text) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: Text(text.toUpperCase(),
          style: AppTextStyles.captionReg.copyWith(
            color: AppColors.blackCaptionGreen,
          )),
    );
  }

  _buildItems(
      context, List<RoleKitEntity> items, bool required, bool showError) {
    return Column(
      children: items.where((item) => item.isMandatory == required).map((item) {
        return CheckBoxCard(
          isChecked: item.confirmed,
          title: item.title,
          errorMessage: showError && !item.confirmed && required
              ? 'please_confirm_availability'.tr()
              : null,
          message: item.confirmed
              ? 'availability_confirmed'.tr()
              : item.needPhoto
                  ? 'confirm_availability_photo'.tr()
                  : null,
          onTap: () {
            BlocProvider.of<RoleKitBloc>(context)
                .add(RoleKiEventChangeState(item));
          },
          padding: const EdgeInsets.only(bottom: 8),
        );
      }).toList(),
    );
  }

  _buildUploadProofItems(context, List<RoleKitEntity> items, bool showError) {
    return Column(
      children: items.where((item) => item.needPhoto).map((item) {
        return UploadImageCard(
          title: item.title,
          onSelectImage: () {
            BlocProvider.of<RoleKitBloc>(context)
                .add(RoleKitEventUploadPhoto(item: item, photoPath: ''));
          },
          onDeleteTap: () {
            BlocProvider.of<RoleKitBloc>(context)
                .add(RoleKitEventDeletePhoto(item));
          },
          onTap: () {},
          imageUrl: item.imageUrl,
          localImagePath: item.localImage,
          inUploading: item.uploading,
          statusColor: item.imageUrl == null
              ? AppColors.statusError
              : AppColors.statusSuccess,
          message: (item.imageUrl == null)
              ? showError
                  ? 'availability_requires_confirmation'.tr()
                  : null
              : 'availability_confirmed'.tr(),
          hasError: showError,
          padding: const EdgeInsets.only(bottom: 8),
        );
      }).toList(),
    );
  }

  Container _buildErrorMessage() {
    return Container(
      margin: const EdgeInsets.only(top: 12),
      padding: const EdgeInsets.all(8),
      decoration: KwBoxDecorations.primaryLight8,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 28,
            width: 28,
            decoration: const BoxDecoration(
                shape: BoxShape.circle, color: AppColors.tintRed),
            child: Center(
              child: Assets.images.icons.alertCircle.svg(),
            ),
          ),
          const Gap(8),
          Expanded(
            child: Text(
              'item_checked_in_box'.tr(),
              style: AppTextStyles.bodyTinyMed
                  .copyWith(color: AppColors.statusError),
            ),
          ),
        ],
      ),
    );
  }
}
