import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart'
    hide ModularWatchExtension;
import 'package:krow_core/core.dart';

import '../blocs/profile_setup/profile_setup_bloc.dart';
import '../widgets/profile_setup_page/profile_setup_basic_info.dart';
import '../widgets/profile_setup_page/profile_setup_experience.dart';
import '../widgets/profile_setup_page/profile_setup_header.dart';
import '../widgets/profile_setup_page/profile_setup_location.dart';

/// Page for setting up the user profile after authentication.
class ProfileSetupPage extends StatefulWidget {
  const ProfileSetupPage({super.key});

  @override
  State<ProfileSetupPage> createState() => _ProfileSetupPageState();
}

class _ProfileSetupPageState extends State<ProfileSetupPage> {
  /// Current step index.
  int _currentStep = 0;

  /// List of steps in the profile setup process.
  List<Map<String, dynamic>> get _steps => <Map<String, dynamic>>[
    <String, dynamic>{
      'id': 'basic',
      'title': t.staff_authentication.profile_setup_page.steps.basic,
      'icon': UiIcons.user,
    },
    <String, dynamic>{
      'id': 'location',
      'title': t.staff_authentication.profile_setup_page.steps.location,
      'icon': UiIcons.mapPin,
    },
    <String, dynamic>{
      'id': 'experience',
      'title': t.staff_authentication.profile_setup_page.steps.experience,
      'icon': UiIcons.briefcase,
    },
  ];

  /// Handles the "Next" button tap logic.
  void _handleNext({
    required BuildContext context,
    required ProfileSetupState state,
    required int stepsCount,
  }) {
    if (_currStepValid(state: state)) {
      if (_currentStep < stepsCount - 1) {
        setState(() => _currentStep++);
      } else {
        BlocProvider.of<ProfileSetupBloc>(
          context,
        ).add(const ProfileSetupSubmitted());
      }
    }
  }

  /// Handles the "Back" button tap logic.
  void _handleBack() {
    if (_currentStep > 0) {
      setState(() => _currentStep--);
    }
  }

  /// Checks if the current step is valid.
  bool _currStepValid({required ProfileSetupState state}) {
    switch (_currentStep) {
      case 0:
        return state.fullName.trim().length >= 2;
      case 1:
        return state.preferredLocations.isNotEmpty;
      case 2:
        return state.skills.isNotEmpty;
      default:
        return true;
    }
  }

  @override
  /// Builds the profile setup page UI.
  Widget build(BuildContext context) {
    final List<Map<String, dynamic>> steps = _steps;

    // Calculate progress
    final double progress = (_currentStep + 1) / steps.length;

    return BlocProvider<ProfileSetupBloc>(
      create: (BuildContext context) => Modular.get<ProfileSetupBloc>(),
      child: BlocConsumer<ProfileSetupBloc, ProfileSetupState>(
        listener: (BuildContext context, ProfileSetupState state) {
          if (state.status == ProfileSetupStatus.success) {
            Modular.to.toStaffHome();
          } else if (state.status == ProfileSetupStatus.failure) {
            UiSnackbar.show(
              context,
              message: translateErrorKey(state.errorMessage ?? t.staff_authentication.profile_setup_page.error_occurred),
              type: UiSnackbarType.error,
              margin: const EdgeInsets.only(bottom: 150, left: 16, right: 16),
            );
          }
        },
        builder: (BuildContext context, ProfileSetupState state) {
          final bool isCreatingProfile =
              state.status == ProfileSetupStatus.loading;

          return Scaffold(
            body: SafeArea(
              child: Column(
                children: <Widget>[
                  // Progress Bar
                  LinearProgressIndicator(value: progress),

                  // Header (Back + Step Count)
                  ProfileSetupHeader(
                    currentStep: _currentStep,
                    totalSteps: steps.length,
                    onBackTap: _handleBack,
                  ),

                  // Step Indicators
                  UiStepIndicator(
                    stepIcons: steps
                        .map(
                          (Map<String, dynamic> step) =>
                              step['icon'] as IconData,
                        )
                        .toList(),
                    currentStep: _currentStep,
                  ),

                  // Content Area
                  Expanded(
                    child: AnimatedSwitcher(
                      duration: const Duration(milliseconds: 300),
                      child: SingleChildScrollView(
                        key: ValueKey<int>(_currentStep),
                        padding: const EdgeInsets.all(UiConstants.space6),
                        child: _buildStepContent(
                          context: context,
                          state: state,
                        ),
                      ),
                    ),
                  ),

                  // Footer
                  Container(
                    padding: const EdgeInsets.all(UiConstants.space6),
                    decoration: const BoxDecoration(
                      border: Border(
                        top: BorderSide(color: UiColors.separatorSecondary),
                      ),
                    ),
                    child: isCreatingProfile
                        ? ElevatedButton(
                            onPressed: null,
                            child: const SizedBox(
                              width: 24,
                              height: 24,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            ),
                          )
                        : UiButton.primary(
                            text: _currentStep == steps.length - 1
                                ? t
                                      .staff_authentication
                                      .profile_setup_page
                                      .complete_setup_button
                                : t.common.continue_text,
                            trailingIcon: _currentStep < steps.length - 1
                                ? UiIcons.arrowRight
                                : null,
                            onPressed: _currStepValid(state: state)
                                ? () => _handleNext(
                                    context: context,
                                    state: state,
                                    stepsCount: steps.length,
                                  )
                                : null,
                          ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  /// Builds the content for the current step.
  Widget _buildStepContent({
    required BuildContext context,
    required ProfileSetupState state,
  }) {
    switch (_currentStep) {
      case 0:
        return ProfileSetupBasicInfo(
          fullName: state.fullName,
          bio: state.bio,
          onFullNameChanged: (String val) => BlocProvider.of<ProfileSetupBloc>(
            context,
          ).add(ProfileSetupFullNameChanged(val)),
          onBioChanged: (String val) => BlocProvider.of<ProfileSetupBloc>(
            context,
          ).add(ProfileSetupBioChanged(val)),
        );
      case 1:
        return ProfileSetupLocation(
          preferredLocations: state.preferredLocations,
          maxDistanceMiles: state.maxDistanceMiles,
          onLocationsChanged: (List<String> val) =>
              BlocProvider.of<ProfileSetupBloc>(
                context,
              ).add(ProfileSetupLocationsChanged(val)),
          onDistanceChanged: (double val) => BlocProvider.of<ProfileSetupBloc>(
            context,
          ).add(ProfileSetupDistanceChanged(val)),
        );
      case 2:
        return ProfileSetupExperience(
          skills: state.skills,
          industries: state.industries,
          onSkillsChanged: (List<String> val) =>
              BlocProvider.of<ProfileSetupBloc>(
                context,
              ).add(ProfileSetupSkillsChanged(val)),
          onIndustriesChanged: (List<String> val) =>
              BlocProvider.of<ProfileSetupBloc>(
                context,
              ).add(ProfileSetupIndustriesChanged(val)),
        );
      default:
        return const SizedBox.shrink();
    }
  }
}
