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 '../navigation/profile_navigator.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/section_title.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 TranslationsStaffProfileEn i18n = t.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.navigateToGetStarted();
          }
        },
        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: Text(
                state.errorMessage ?? 'An error occurred',
                style: UiTypography.body1r.copyWith(
                  color: UiColors.destructive,
                ),
              ),
            );
          }

          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, -24),
                  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,
                              completed: profile.phone != null,
                              onTap: () => Modular.to.pushPersonalInfo(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.phone,
                              label: i18n.menu_items.emergency_contact,
                              completed: false,
                              onTap: () => Modular.to.pushEmergencyContact(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.briefcase,
                              label: i18n.menu_items.experience,
                              completed: false,
                              onTap: () => Modular.to.pushExperience(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.user,
                              label: i18n.menu_items.attire,
                              completed: false,
                              onTap: () => Modular.to.pushAttire(),
                            ),
                          ],
                        ),
                        const SizedBox(height: UiConstants.space6),
                        SectionTitle(i18n.sections.compliance),
                        ProfileMenuGrid(
                          crossAxisCount: 3,
                          children: [
                            ProfileMenuItem(
                              icon: UiIcons.file,
                              label: i18n.menu_items.documents,
                              completed: false,
                              onTap: () => Modular.to.pushDocuments(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.shield,
                              label: i18n.menu_items.certificates,
                              completed: false,
                              onTap: () => Modular.to.pushCertificates(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.file,
                              label: i18n.menu_items.tax_forms,
                              completed: false,
                              onTap: () => Modular.to.pushTaxForms(),
                            ),
                          ],
                        ),
                        const SizedBox(height: UiConstants.space6),
                        SectionTitle(i18n.sections.level_up),
                        ProfileMenuGrid(
                          crossAxisCount: 3,
                          children: [
                            ProfileMenuItem(
                              icon: UiIcons.sparkles,
                              label: i18n.menu_items.krow_university,
                              onTap: () => Modular.to.pushKrowUniversity(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.briefcase,
                              label: i18n.menu_items.trainings,
                              onTap: () => Modular.to.pushTrainings(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.target,
                              label: i18n.menu_items.leaderboard,
                              onTap: () => Modular.to.pushLeaderboard(),
                            ),
                          ],
                        ),
                        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.pushBankAccount(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.creditCard,
                              label: i18n.menu_items.payments,
                              onTap: () => Modular.to.navigate('/worker-main/payments'),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.clock,
                              label: i18n.menu_items.timecard,
                              onTap: () => Modular.to.pushTimecard(),
                            ),
                          ],
                        ),
                        const SizedBox(height: UiConstants.space6),
                        SectionTitle(i18n.sections.support),
                        ProfileMenuGrid(
                          crossAxisCount: 3,
                          children: [
                            ProfileMenuItem(
                              icon: UiIcons.help,
                              label: i18n.menu_items.faqs,
                              onTap: () => Modular.to.pushFaqs(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.shield,
                              label: i18n.menu_items.privacy_security,
                              onTap: () => Modular.to.pushPrivacy(),
                            ),
                            ProfileMenuItem(
                              icon: UiIcons.messageCircle,
                              label: i18n.menu_items.messages,
                              onTap: () => Modular.to.pushMessages(),
                            ),
                          ],
                        ),
                        const SizedBox(height: UiConstants.space6),
                        LogoutButton(
                          onTap: () => _onSignOut(cubit, state),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
