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/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/kw_app_bar.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_input.dart';
import 'package:krow/features/profile/bank_account/domain/bloc/bank_account_bloc.dart';

@RoutePage()
class BankAccountEditScreen extends StatefulWidget {
  const BankAccountEditScreen({super.key});

  @override
  State<BankAccountEditScreen> createState() => _BankAccountEditScreenState();
}

class _BankAccountEditScreenState extends State<BankAccountEditScreen> {
  Map<String, BankAccField>? bankAccInfo;
  final Map<String, TextEditingController> _controllers = {};

  var showInputError = false;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      bankAccInfo = Map.of(
          BlocProvider.of<BankAccountBloc>(context).state.mapFromBankAccount());

      bankAccInfo?.keys.forEach((key) {
        _controllers[key] =
            TextEditingController(text: bankAccInfo?[key]?.value);
      });
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<BankAccountBloc, BankAccountState>(
      listener: (context, state) {
        if (state.success) {
          context.router.maybePop();
        }
      },
      builder: (context, state) {
        return Scaffold(
          appBar: KwAppBar(
            titleText: 'edit_bank_account'.tr(),
            showNotification: true,
          ),
          body: ScrollLayoutHelper(
            padding: const EdgeInsets.all(16),
            upperWidget: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'edit_information_below'.tr(),
                  style: AppTextStyles.bodySmallReg
                      .copyWith(color: AppColors.blackGray),
                ),
                const Gap(24),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: KwBoxDecorations.primaryLight12,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildCardHeader(context, 'account_details'.tr()),
                      ...(bankAccInfo?.entries
                              .take(4)
                              .map((entry) =>
                                  _buildInput(entry.key, entry.value))
                              .toList() ??
                          [])
                    ],
                  ),
                ),
                const Gap(12),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: KwBoxDecorations.primaryLight12,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildCardHeader(context, 'billing_address'.tr()),
                      ...(bankAccInfo?.entries
                              .skip(4)
                              .map((entry) =>
                                  _buildInput(entry.key, entry.value))
                              .toList() ??
                          [])
                    ],
                  ),
                ),
                const Gap(24),
              ],
            ),
            lowerWidget: KwButton.primary(
              label: 'save_changes'.tr(),
              onPressed: () {
                if (bankAccInfo?.values.any((element) =>
                        !element.optional &&
                        (element.value?.isEmpty ?? false)) ??
                    false) {
                  setState(() {
                    showInputError = true;
                  });
                  return;
                }

                var newAcc = bankAccInfo?.map((key, value) => MapEntry(
                      key,
                      _controllers[key]?.text ?? '',
                    ));

                BlocProvider.of<BankAccountBloc>(context)
                    .add(BankAccountEventUpdate(newAcc!));
              },
            ),
          ),
        );
      },
    );
  }

  Widget _buildCardHeader(BuildContext context, String title) {
    return Text(
      title,
      style: AppTextStyles.bodyMediumMed,
    );
  }

  Widget _buildInput(String key, BankAccField field) {
    var hasError = !field.optional &&
        (_controllers[key]?.text.isEmpty ?? false) &&
        showInputError;
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: KwTextInput(
        hintText: '',
        title: field.title,
        onChanged: (value) {
          setState(() {
            field.value = value;
          });

        },
        helperText: hasError ? 'field_cant_be_empty'.tr() : null,
        showError: hasError,
        controller: _controllers[key],
      ),
    );
  }
}
