import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.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/features/auth/domain/bloc/auth_bloc.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/ui_kit/kw_app_bar.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/scroll_layout_helper.dart';
import 'package:pinput/pinput.dart';

@RoutePage()
class CodeVerificationScreen extends StatefulWidget {
  const CodeVerificationScreen({
    super.key,
  });

  @override
  State<CodeVerificationScreen> createState() => _CodeVerificationScreenState();
}

class _CodeVerificationScreenState extends State<CodeVerificationScreen> {
  late final TapGestureRecognizer resendRecognizer;
  String code = '';

  String _title(AuthState state) {
    switch (state.authType) {
      case AuthType.login:
        return 'Welcome Back!'.tr();
      default:
        return 'Enter Verification Code'.tr();
    }
  }

  String get _subTitle {
    return 'Enter the 6-digit'.tr();
  }

  @override
  void initState() {
    super.initState();

    resendRecognizer = TapGestureRecognizer()
      ..onTap = () {
        BlocProvider.of<AuthBloc>(context).add(const AuthSendSmsEvent(null));
      };
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: KwAppBar(
        titleText: 'Phone Verification'.tr(),
        showNotification: false,
      ),
      body: BlocBuilder<AuthBloc, AuthState>(
        builder: (context, state) {
          return 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,
                  style: AppTextStyles.bodyMediumReg
                      .copyWith(color: AppColors.blackGray),
                ),
                const Gap(24),
                _buildCodeInput(context, state),
                const Gap(12),
                _buildCodeControl(context, state),
              ],
            ),
            lowerWidget: _buildControlNavButton(context, state.authType),
          );
        },
      ),
    );
  }

  Widget _buildControlNavButton(BuildContext context, authType) {
    return Column(
      children: [
        KwButton.primary(
          label: 'Enter and Continue'.tr(),
          disabled: code.length != 6,
          onPressed: () {
            BlocProvider.of<AuthBloc>(context).add(AuthEventConfirmCode(code));
          },
        ),
        const Gap(36),
        if (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 = () {
                      BlocProvider.of<AuthBloc>(context)
                          .add(const AuthTypeChangedEvent(AuthType.register));
                      // context.maybePop();
                    },
                )
              ],
            ),
          ),
          const Gap(20),
        ]
      ],
    );
  }

  Widget _buildCodeInput(BuildContext context, AuthState state) {
    final defaultPinTheme = PinTheme(
      width: 43,
      height: 52,
      textStyle: AppTextStyles.headingH1,
      decoration: BoxDecoration(
        border: Border.all(color: AppColors.grayStroke),
        borderRadius: BorderRadius.circular(8),
      ),
    );

    var focusedPinTheme = defaultPinTheme.copyWith(
      decoration: BoxDecoration(
        border: Border.all(color: AppColors.blackBlack),
        borderRadius: BorderRadius.circular(8),
      ),
    );

    var errorPinTheme = defaultPinTheme.copyWith(
      textStyle: AppTextStyles.headingH1.copyWith(color: AppColors.statusError),
      decoration: BoxDecoration(
        border: Border.all(color: AppColors.statusError),
        borderRadius: BorderRadius.circular(8),
      ),
    );

    return Pinput(
      length: 6,
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      onCompleted: (pin) =>
          BlocProvider.of<AuthBloc>(context).add(AuthEventConfirmCode(code)),
      onChanged: (pin) {
        setState(() {
          state.codeError = null;
          code = pin;
        });
      },
      defaultPinTheme: defaultPinTheme,
      focusedPinTheme: focusedPinTheme,
      errorPinTheme: errorPinTheme,
      forceErrorState: state.codeError != null,
    );
  }

  _buildCodeControl(BuildContext context, AuthState state) {
    return Row(
      children: [
        if (state.codeError != null) ...[
          Expanded(
            child: Text(
              state.codeError!,
              style: AppTextStyles.bodyTinyMed
                  .copyWith(color: AppColors.statusError),
            ),
          ),
          const Gap(24),
        ],
        RichText(
          text: TextSpan(
            children: [
              if (state.codeError == null)
                 TextSpan(
                  text: '${'Didn`t get the code?'.tr()} ',
                  style: AppTextStyles.bodyTinyMed,
                ),
              TextSpan(
                text: 'Resend Code'.tr(),
                recognizer: resendRecognizer,
                style: AppTextStyles.bodyTinyMed.copyWith(
                    decoration: TextDecoration.underline,
                    fontWeight: FontWeight.w600),
              ),
              if (state.resendTimeout > 0)
                TextSpan(
                  text: ' ${'in'.tr()} ${state.resendTimeout} s',
                  recognizer: resendRecognizer,
                  style: AppTextStyles.bodyTinyMed.copyWith(
                      decoration: TextDecoration.underline,
                      fontWeight: FontWeight.w600),
                ),
            ],
          ),
        )
      ],
    );
  }
}
