// Flutter imports:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

// Project imports:
import 'package:remever/common/resources.dart';
import 'package:remever/common/widgets/typography.dart';
import 'package:remever/common/widgets/wspace.dart';
import 'package:remever/components/extensions/context.dart';
import 'package:remever/gen/assets.gen.dart';
import 'package:remever/screens/auth/cubit/auth_cubit.dart';
import 'package:remever/screens/auth/widgets/auth_text_field.dart';
import 'package:remever/widgets/primary_button.dart';

///
/// Отрисовка экрана авторизации по e-mail
///
class EmailAuth extends StatefulWidget {
  const EmailAuth({super.key});

  @override
  EmailAuthState createState() => EmailAuthState();
}

class EmailAuthState extends State<EmailAuth> {
  final TextEditingController _emailController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  // Константы для стилей и отступов
  static final EdgeInsetsGeometry _padding = EdgeInsets.all(16).r;
  static final _regular14 = Regular14px();
  static final _medium14 = Medium14px();

  @override
  void dispose() {
    _emailController.dispose();
    super.dispose();
  }

  void _onEnterTap() async {
    if (!_formKey.currentState!.validate()) return;
    await context.read<AuthCubit>().login(_emailController.text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bg,
      body: Padding(
        padding: _padding,
        child: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              HSpace(148),
              _buildLogo(),
              const HSpace(60),
              _buildEmailField(),
              const HSpace(24),
              _buildInstructions(),
              HSpace(145),
              _buildLoginButton(),
              const HSpace(104),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLogo() {
    return Assets.images.logo.image(width: 308.w, height: 100.h);
  }

  Widget _buildEmailField() {
    return Form(
      key: _formKey,
      child: AuthTextField(email: _emailController, autofocus: true),
    );
  }

  Widget _buildInstructions() {
    return AppTypography(
      'Для авторизации в приложении мы отправим код на указанный e-mail',
      type: _regular14,
      maxLines: 3,
    );
  }

  Widget _buildLoginButton() {
    return PrimaryButton(
      onTap: _onEnterTap,
      child: AppTypography('Войти', type: _medium14, color: AppColors.white),
    );
  }
}
