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/application/common/int_extensions.dart';
import 'package:krow/core/application/common/validators/skill_exp_validator.dart';
import 'package:krow/core/data/enums/staff_skill_enums.dart';
import 'package:krow/core/data/models/skill.dart';
import 'package:krow/core/data/models/staff_role.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/dialogs/kw_dialog.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_dropdown.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_input.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_option_selector.dart';
import 'package:krow/features/profile/role/domain/bloc/role_bloc.dart';
import 'package:krow/features/profile/role/domain/bloc/role_event.dart';
import 'package:krow/features/profile/role/presentation/widgets/exp_slider_widget.dart';

class RoleEditCardWidget extends StatefulWidget {
  final StaffRole role;

  final int index;

  final List<Skill> skills;

  final bool canDelete;

  final bool mustShowWarningDialog;

  const RoleEditCardWidget(
      {super.key,
      required this.role,
      required this.index,
      required this.skills,
      required this.canDelete,
      this.mustShowWarningDialog = false});

  @override
  State<RoleEditCardWidget> createState() => _RoleEditCardWidgetState();
}

class _RoleEditCardWidgetState extends State<RoleEditCardWidget> {
  String? experienceError;
  late TextEditingController textEditingController;

  @override
  void initState() {
    textEditingController =
        TextEditingController(text: widget.role.experience.toString());

    textEditingController.addListener(() {
      final value = textEditingController.text;
      setState(() {
        experienceError = SkillExpValidator.validate(value);
      });

      var exp = int.tryParse(value);
      if (exp != null && experienceError == null) {
        BlocProvider.of<RoleBloc>(context).add(RoleUpdateEvent(
          widget.role.copyWith(experience: exp),
        ));
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _header(),
        const Gap(16),
        _skillDropDown(context),
        const Gap(16),
        KwOptionSelector(
            selectedIndex: widget.role.level?.index ?? 0,
            backgroundColor: AppColors.graySecondaryFrame,
            onChanged: (index) {
              BlocProvider.of<RoleBloc>(context).add(RoleUpdateEvent(
                widget.role.copyWith(level: StaffSkillLevel.values[index]),
              ));
            },
            title: 'level'.tr(),
            items: [
              'Beginner'.tr(),
              'Skilled'.tr(),
              'Professional'.tr(),
            ]),
        const Gap(16),
        KwTextInput(
            controller: textEditingController,
            title: 'years_of_exp'.tr(),
            helperText: experienceError,
            showError: experienceError != null,
            onChanged: (value) {}),
        const Gap(12),
        ExpSliderWidget(
          initialValue: widget.role.experience ?? 1,
          onChanged: (value) {
            setState(() {
              textEditingController.text = value.toString();
            });
          },
        ),
        KwButton.primary(
          disabled: widget.role.skill == null,
          label: 'save_changes'.tr(),
          onPressed: _onSaveChanges,
        ),
        const Gap(12),
      ],
    );
  }

  Widget _skillDropDown(BuildContext context) {
    return IgnorePointer(
      ignoring: widget.role.status != null,
      child: KwDropdown<Skill>(
          horizontalPadding: 28,
          title: 'role'.tr(),
          hintText: 'select_role'.tr(),
          selectedItem: widget.role.skill == null
              ? null
              : KwDropDownItem(
                  data: widget.role.skill!,
                  title: widget.role.skill?.name ?? ''),
          items: widget.skills
              .map((skill) => KwDropDownItem(data: skill, title: skill.name)),
          onSelected: (skill) {
            BlocProvider.of<RoleBloc>(context).add(RoleUpdateEvent(
              widget.role.copyWith(skill: skill),
            ));
          }),
    );
  }

  Row _header() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          '${(widget.index + 1).toOrdinal()} ${'role_details'.tr()}:',
          style: AppTextStyles.bodyMediumMed,
        ),
        if (widget.canDelete)
          GestureDetector(
            onTap: () async {
              BlocProvider.of<RoleBloc>(context)
                  .add(RoleDeleteEvent(widget.role));
            },
            child: Container(
              color: Colors.transparent,
              height: 24,
              width: 24,
              child: Center(
                child: Assets.images.icons.delete.svg(
                  height: 16,
                  width: 16,
                  colorFilter: const ColorFilter.mode(
                      AppColors.statusError, BlendMode.srcIn),
                ),
              ),
            ),
          ),
      ],
    );
  }

  void _onSaveChanges() {
    if (widget.mustShowWarningDialog &&
        widget.role.status != StaffSkillStatus.pending) {
      _showWarningReviewDialog(context).then(
        (value) {
          if (value == true && context.mounted) {
            BlocProvider.of<RoleBloc>(context)
                .add(RoleSaveChangesEvent(widget.role));
          }
        },
      );
    } else {
      BlocProvider.of<RoleBloc>(context).add(RoleSaveChangesEvent(widget.role));
    }
  }

  Future<bool?> _showWarningReviewDialog(BuildContext context) {
    return KwDialog.show<bool>(
        context: context,
        icon: Assets.images.icons.alertTriangle,
        state: KwDialogState.neutral,
        title: 'role_change'.tr(),
        message: 'change_u_role'.tr(),
        child: Text(
          'wont_to_proceed'.tr(),
          style: AppTextStyles.bodyMediumMed,
        ),
        primaryButtonLabel: 'Continue'.tr(),
        secondaryButtonLabel: 'cancel'.tr(),
        onPrimaryButtonPressed: (BuildContext dialogContext) {
          dialogContext.maybePop(true);
        },
        onSecondaryButtonPressed: (BuildContext dialogContext) {
          dialogContext.maybePop(false);
        });
  }
}
