import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/application/routing/routes.gr.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_phone_input.dart';
import 'package:krow/features/auth/domain/bloc/auth_bloc.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

@RoutePage()
class PhoneVerificationScreen extends StatefulWidget {
  const PhoneVerificationScreen({super.key, required this.type});

  final AuthType type;

  @override
  State<PhoneVerificationScreen> createState() =>
      _PhoneVerificationScreenState();
}

class _PhoneVerificationScreenState extends State<PhoneVerificationScreen> {
  late TextEditingController _phoneController;

  String? _appBarTitle(AuthState state) {
    switch (state.authType) {
      case AuthType.login:
        return null;
      case AuthType.register:
        return 'Phone Verification'.tr();
      case null:
        return ' ';
    }
  }

  String _title(AuthState state) {
    switch (state.authType) {
      case AuthType.login:
        return 'Welcome Back!'.tr();
      case AuthType.register:
        return "Let's Get Started!".tr();
      case null:
        return '';
    }
  }

  String _subTitle(AuthState state) {
    switch (state.authType) {
      case AuthType.login:
        return 'Log in to find work opportunities that match your skills'.tr();
      case AuthType.register:
        return 'Verify your phone number to activate your account'.tr();
      case null:
        return '';
    }
  }

  @override
  void initState() {
    super.initState();
    _phoneController = TextEditingController(text: '+1');
    _phoneController.addListener(() {
      context.read<AuthBloc>().add(const AuthPhoneChangedEvent());
    });

    _debug();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<AuthBloc, AuthState>(listener: (context, state) {
      if (state.needClearPhone) {
        _phoneController.clear();
      }
      if (state.needNavigateToCodeVerification) {
        context.router.push(const CodeVerificationRoute());
      }
    }, builder: (context, state) {
      return ModalProgressHUD(
        inAsyncCall: state.isLoading,
        child: Scaffold(
          appBar: KwAppBar(
            titleText: _appBarTitle(state),
            showNotification: false,
          ),
          body: ScrollLayoutHelper(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            upperWidget: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                const Gap(20),
                Text(
                  _title(state),
                  style: AppTextStyles.headingH1,
                ),
                const Gap(8),
                Text(
                  _subTitle(state),
                  style: AppTextStyles.bodyMediumReg
                      .copyWith(color: AppColors.blackGray),
                ),
                const Gap(24),
                KwPhoneInput(
                  title: 'Phone Number'.tr(),
                  controller: _phoneController,
                  error: state.phoneError,
                ),
                const Gap(24),
              ],
            ),
            lowerWidget: _buildControNavButton(context, state),
          ),
        ),
      );
    });
  }

  Widget _buildControNavButton(context, AuthState state) {
    return Column(
      children: [
        KwButton.primary(
          label:
              '${'Continue'.tr()} ${state.resendTimeout > 0 ? '${'in'.tr()} ${state.resendTimeout}' : ''}',
          disabled: _phoneController.text.isEmpty || state.resendTimeout > 0,
          onPressed: () => BlocProvider.of<AuthBloc>(context).add(
            AuthSendSmsEvent(_phoneController.text),
          ),
        ),
        const Gap(36),
        if (state.authType == AuthType.login) ...[
          RichText(
            text: TextSpan(
              text: '${'New here?'.tr()} ',
              style: AppTextStyles.bodyMediumReg
                  .copyWith(color: AppColors.blackGray),
              children: [
                TextSpan(
                  text: 'Create an account'.tr(),
                  style: AppTextStyles.bodyMediumSmb,
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      _phoneController.text = '+1';
                      BlocProvider.of<AuthBloc>(context).add(
                        const AuthTypeChangedEvent(AuthType.register),
                      );
                    },
                )
              ],
            ),
          ),
          const Gap(20),
        ]
      ],
    );
  }

  void _debug() {
    if (!kDebugMode) return;
    _phoneController.text = const String.fromEnvironment(
      'DEBUG_PHONE',
      defaultValue: '+1',
    );
  }
}
