import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart' hide ReadContext;
import 'package:flutter_modular/flutter_modular.dart';
import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:krow_domain/krow_domain.dart';

import '../blocs/profile_cubit.dart';
import '../blocs/profile_state.dart';
import 'package:krow_core/core.dart';
import '../widgets/logout_button.dart';
import '../widgets/profile_menu_grid.dart';
import '../widgets/profile_menu_item.dart';
import '../widgets/profile_header.dart';
import '../widgets/reliability_score_bar.dart';
import '../widgets/reliability_stats_card.dart';
import '../widgets/reliability_stats_card.dart';
import '../widgets/section_title.dart';
import '../widgets/language_selector_bottom_sheet.dart';

/// The main Staff Profile page.
///
/// This page displays the staff member's profile including their stats,
/// reliability score, and various menu sections for onboarding, compliance,
/// learning, finance, and support.
///
/// It follows Clean Architecture with BLoC for state management.
class StaffProfilePage extends StatelessWidget {
  /// Creates a [StaffProfilePage].
  const StaffProfilePage({super.key});

  String _mapStatusToLevel(StaffStatus status) {
    switch (status) {
      case StaffStatus.active:
      case StaffStatus.verified:
        return 'Krower I';
      case StaffStatus.pending:
      case StaffStatus.completedProfile:
        return 'Pending';
      default:
        return 'New';
    }
  }

  void _onSignOut(ProfileCubit cubit, ProfileState state) {
    if (state.status != ProfileStatus.loading) {
      cubit.signOut();
    }
  }

  @override
  Widget build(BuildContext context) {
    final i18n = Translations.of(context).staff.profile;
    final ProfileCubit cubit = Modular.get<ProfileCubit>();

    // Load profile data on first build
    if (cubit.state.status == ProfileStatus.initial) {
      cubit.loadProfile();
    }

    return Scaffold(
      body: BlocConsumer<ProfileCubit, ProfileState>(
        bloc: cubit,
        listener: (context, state) {
          if (state.status == ProfileStatus.signedOut) {
            Modular.to.toGetStarted();
          } else if (state.status == ProfileStatus.error &&
              state.errorMessage != null) {
            UiSnackbar.show(
              context,
              message: translateErrorKey(state.errorMessage!),
              type: UiSnackbarType.error,
            );
          }
        },
        builder: (context, state) {
          // Show loading spinner if status is loading
            if (state.status == ProfileStatus.loading) {
              return const Center(child: CircularProgressIndicator());
            }

            if (state.status == ProfileStatus.error) {
            return Center(
              child: Padding(
                padding: const EdgeInsets.all(UiConstants.space4),
                child: Text(
                  state.errorMessage != null
                      ? translateErrorKey(state.errorMessage!)
                      : 'An error occurred',
                  textAlign: TextAlign.center,
                  style: UiTypography.body1r.copyWith(
                    color: UiColors.textSecondary,
                  ),
                ),
              ),
            );
          }

          final profile = state.profile;
          if (profile == null) {
            return const Center(child: CircularProgressIndicator());
          }

          return SingleChildScrollView(
            padding: const EdgeInsets.only(bottom: UiConstants.space16),
            child: Column(
              children: [
                ProfileHeader(
                  fullName: profile.name,
                  level: _mapStatusToLevel(profile.status),
                  photoUrl: profile.avatar,
                  onSignOutTap: () => _onSignOut(cubit, state),
                ),
                Transform.translate(
                  offset: const Offset(0, -UiConstants.space6),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: UiConstants.space5,
                    ),
                    child: Column(
                      children: [
                        ReliabilityStatsCard(
                          totalShifts: profile.totalShifts,
                          averageRating: profile.averageRating,
                          onTimeRate: profile.onTimeRate,
                          noShowCount: profile.noShowCount,
                          cancellationCount: profile.cancellationCount,
                        ),
                        const SizedBox(height: UiConstants.space6),
                        ReliabilityScoreBar(
                          reliabilityScore: profile.reliabilityScore,
                        ),
                        const SizedBox(height: UiConstants.space6),
                        SectionTitle(i18n.sections.onboarding),
                        ProfileMenuGrid(
                          crossAxisCount: 3,
                          
                          children: [
                            ProfileMenuItem(
                              icon: UiIcons.user,
                              label: i18n.menu_items.personal_info,
                              onTap: () => Modular.to.toPersonalInfo(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.phone,
                              label: i18n.menu_items.emergency_contact,
                              onTap: () => Modular.to.toEmergencyContact(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.briefcase,
                              label: i18n.menu_items.experience,
                              onTap: () => Modular.to.toExperience(),
                            ),
                          ],
                        ),
                        const SizedBox(height: UiConstants.space6),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SectionTitle(i18n.sections.compliance),
                            ProfileMenuGrid(
                              crossAxisCount: 3,
                              children: [
                                ProfileMenuItem(
                                  icon: UiIcons.file,
                                  label: i18n.menu_items.tax_forms,
                                  onTap: () => Modular.to.toTaxForms(),
                                ),
                              ],
                            ),
                          ],
                        ),
                        const SizedBox(height: UiConstants.space6),
                        SectionTitle(i18n.sections.finance),
                        ProfileMenuGrid(
                          crossAxisCount: 3,
                          children: [
                            ProfileMenuItem(
                              icon: UiIcons.building,
                              label: i18n.menu_items.bank_account,
                              onTap: () => Modular.to.toBankAccount(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.creditCard,
                              label: i18n.menu_items.payments,
                              onTap: () => Modular.to.toPayments(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.clock,
                              label: i18n.menu_items.timecard,
                              onTap: () => Modular.to.toTimeCard(),
                            ),
                          ],
                        ),
                        const SizedBox(height: UiConstants.space6),
                        SectionTitle(
                          i18n.header.title.contains("Perfil") ? "Ajustes" : "Settings",
                        ),
                        ProfileMenuGrid(
                          crossAxisCount: 3,
                          children: [
                            ProfileMenuItem(
                              icon: UiIcons.globe,
                              label: i18n.header.title.contains("Perfil") ? "Idioma" : "Language",
                              onTap: () {
                                showModalBottomSheet(
                                  context: context,
                                  builder: (context) => const LanguageSelectorBottomSheet(),
                                );
                              },
                            ),
                          ],
                        ),
                        const SizedBox(height: UiConstants.space6),
                        LogoutButton(
                          onTap: () => _onSignOut(cubit, state),
                        ),
                        const SizedBox(height: UiConstants.space12),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
