import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:design_system/design_system.dart';
import 'package:core_localization/core_localization.dart';
import 'package:krow_domain/krow_domain.dart';
// ignore: depend_on_referenced_packages

import '../blocs/bank_account_cubit.dart';
import '../blocs/bank_account_state.dart';
import '../navigation/staff_bank_account_navigator.dart';
import '../widgets/add_account_form.dart';

class BankAccountPage extends StatelessWidget {
  const BankAccountPage({super.key});

  @override
  Widget build(BuildContext context) {
    final BankAccountCubit cubit = Modular.get<BankAccountCubit>();
    // Load accounts initially
    if (cubit.state.status == BankAccountStatus.initial) {
      cubit.loadAccounts();
    }

    // final t = AppTranslation.current; // Replaced
    final Translations t = Translations.of(context);
    final dynamic strings = t.staff.profile.bank_account_page;

    return Scaffold(
      backgroundColor: UiColors.background,
      appBar: AppBar(
        backgroundColor: UiColors.background, // Was surface
        elevation: 0,
        leading: IconButton(
          icon: const Icon(UiIcons.arrowLeft, color: UiColors.textSecondary),
          onPressed: () => Modular.to.popPage(),
        ),
        title: Text(
          strings.title,
          style: UiTypography.headline3m.copyWith(color: UiColors.textPrimary),
        ),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(1.0),
          child: Container(color: UiColors.border, height: 1.0),
        ),
      ),
      body: BlocConsumer<BankAccountCubit, BankAccountState>(
        bloc: cubit,
        listener: (BuildContext context, BankAccountState state) {
          if (state.status == BankAccountStatus.accountAdded) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(
                  strings.account_added_success,
                  style: UiTypography.body2r.textPrimary,
                ),
                backgroundColor: UiColors.tagSuccess,
                behavior: SnackBarBehavior.floating,
                duration: const Duration(seconds: 3),
              ),
            );
          }
        },
        builder: (BuildContext context, BankAccountState state) {
          if (state.status == BankAccountStatus.loading && state.accounts.isEmpty) {
            return const Center(child: CircularProgressIndicator());
          }

          if (state.status == BankAccountStatus.error) {
            return Center(child: Text(state.errorMessage ?? 'Error'));
          }

          return Column(
            children: <Widget>[
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(UiConstants.space4),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      _buildSecurityNotice(strings),
                      const SizedBox(height: UiConstants.space6),
                      Text(
                        strings.linked_accounts,
                        style: UiTypography.headline4m.copyWith(color: UiColors.textPrimary),
                      ),
                      const SizedBox(height: UiConstants.space3),
                      ...state.accounts.map((BankAccount a) => _buildAccountCard(a, strings)), // Added type

                      // Add extra padding at bottom
                      const SizedBox(height: 80),
                    ],
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.all(UiConstants.space5),
                decoration: const BoxDecoration(
                  color: UiColors.background, // Was surface
                  border: Border(top: BorderSide(color: UiColors.border)),
                ),
                child: SafeArea(
                  child: UiButton.primary(
                    text: strings.add_account,
                    leadingIcon: UiIcons.add,
                    onPressed: () {
                      showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return Dialog(
                            backgroundColor: Colors.transparent,
                            child: AddAccountForm(
                              strings: strings,
                              onSubmit: (String bankName, String routing, String account, String type) {
                                cubit.addAccount(
                                  bankName: bankName,
                                  routingNumber: routing,
                                  accountNumber: account,
                                  type: type,
                                );
                                Modular.to.popPage();
                              },
                              onCancel: () {
                                Modular.to.popPage();
                              },
                            ),
                          );
                        },
                      );
                    },
                    fullWidth: true,
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildSecurityNotice(dynamic strings) {
    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.primary.withOpacity(0.08),
        borderRadius: BorderRadius.circular(UiConstants.radiusBase),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          const Icon(UiIcons.shield, color: UiColors.primary, size: 20),
          const SizedBox(width: UiConstants.space3),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  strings.secure_title,
                  style: UiTypography.body2r.copyWith( // Was body2
                    fontWeight: FontWeight.w500,
                    color: UiColors.textPrimary,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  strings.secure_subtitle,
                  style: UiTypography.body3r.copyWith(color: UiColors.textSecondary), // Was bodySmall
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAccountCard(BankAccount account, dynamic strings) {
    final bool isPrimary = account.isPrimary;
    const Color primaryColor = UiColors.primary;

    return Container(
      margin: const EdgeInsets.only(bottom: UiConstants.space3),
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.bgPopup, // Was surface, using bgPopup (white) for card
        borderRadius: BorderRadius.circular(UiConstants.radiusBase),
        border: Border.all(
          color: isPrimary ? primaryColor : UiColors.border,
          width: isPrimary ? 2 : 1,
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            children: <Widget>[
              Container(
                width: 48,
                height: 48,
                decoration: BoxDecoration(
                  color: primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(UiConstants.radiusBase),
                ),
                child: const Center(
                  child: Icon(
                    UiIcons.building,
                    color: primaryColor,
                    size: 24,
                  ),
                ),
              ),
              const SizedBox(width: UiConstants.space3),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    account.bankName,
                    style: UiTypography.body2r.copyWith( // Was body2
                      fontWeight: FontWeight.w500,
                      color: UiColors.textPrimary,
                    ),
                  ),
                  Text(
                    strings.account_ending(
                      last4: account.last4?.isNotEmpty == true
                          ? account.last4!
                          : '----',
                    ),
                    style: UiTypography.body2r.copyWith( // Was body2
                      color: UiColors.textSecondary,
                    ),
                  ),
                ],
              ),
            ],
          ),
          if (isPrimary)
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: primaryColor.withOpacity(0.15),
                borderRadius: BorderRadius.circular(20),
              ),
              child: Row(
                children: <Widget>[
                  const Icon(UiIcons.check, size: 12, color: primaryColor),
                  const SizedBox(width: 4),
                  Text(
                    strings.primary,
                    style: UiTypography.body3r.copyWith( // Was bodySmall
                      fontWeight: FontWeight.w500,
                      color: primaryColor,
                    ),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }
}
