import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:fluttericon/font_awesome5_icons.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:unit2/screens/unit2/login/components/update_required.dart';
import 'package:unit2/utils/alerts.dart';
import 'package:unit2/utils/internet_time_out.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/error_state.dart';
import '../../../bloc/user/user_bloc.dart';
import '../../../widgets/splash_screen.dart';
import '../../../widgets/wave.dart';
import '../../../utils/global.dart';
import '../../../theme-data.dart/colors.dart';
import '../../../theme-data.dart/form-style.dart';
import '../../../theme-data.dart/btn-style.dart';
import './components/login-via-qr-label.dart';
import './functions/press-again-to-exit.dart';

class UniT2Login extends StatefulWidget {
  const UniT2Login({super.key});

  @override
  State<UniT2Login> createState() => _UniT2LoginState();
}

class _UniT2LoginState extends State<UniT2Login> {
  final _formKey = GlobalKey<FormBuilderState>();
  bool showSuffixIcon = false;
  bool _showPassword = true;
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: pressAgainToExit,
      child: Scaffold(
        body: ProgressHUD(
          child: BlocConsumer<UserBloc, UserState>(listener: (context, state) {
            if (state is UserLoggedIn) {
              final progress = ProgressHUD.of(context);
              progress!.dismiss();
              Navigator.pushReplacementNamed(context, '/module-screen');
            }
            if (state is UuidLoaded) {
              final progress = ProgressHUD.of(context);
              progress!.dismiss();
              Navigator.pushNamed(context, '/qr-login');
            }
            if (state is UserError) {
              final progress = ProgressHUD.of(context);
              progress!.dismiss();
            }
            if (state is InternetTimeout) {
              final progress = ProgressHUD.of(context);
              progress!.dismiss();
            }
            if (state is InvalidCredentials) {
              final progress = ProgressHUD.of(context);
              progress!.dismiss();
              errorAlert(context, "Error Login", state.message);
              context.read<UserBloc>().add(LoadVersion());
            }
          }, builder: (context, state) {
            if (state is VersionLoaded) {
              return Builder(builder: (context) {
                if (state.versionInfo!.version != state.apkVersion) {
                  return SizedBox(
                    child: SingleChildScrollView(
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          Positioned(
                              bottom: 0,
                              right: 0,
                              child:
                                  WaveReverse(height: blockSizeVertical * 7)),
                          SizedBox(
                            height: blockSizeVertical * 100,
                            child: FormBuilder(
                              key: _formKey,
                              child: Padding(
                                padding:
                                    const EdgeInsets.symmetric(horizontal: 25),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    SvgPicture.asset(
                                      'assets/svgs/logo.svg',
                                      height: blockSizeVertical * 12,
                                      allowDrawingOutsideViewBox: true,
                                      color: primary,
                                    ),

                                    Text(
                                      welcome,
                                      style: TextStyle(
                                          fontSize: blockSizeVertical * 4,
                                          fontWeight: FontWeight.w600),
                                    ),
                                    Text(unitApp,
                                        style: TextStyle(
                                            fontSize: blockSizeVertical * 6,
                                            fontWeight: FontWeight.w800,
                                            letterSpacing: .2,
                                            height: 1,
                                            color: primary)),
                                    // Text(
                                    //   loginToContinue,
                                    //   style: TextStyle(
                                    //       fontSize: blockSizeVertical * 1.7,
                                    //       height: 1.5,
                                    //       fontWeight: FontWeight.w600),
                                    // ),
                                    SizedBox(
                                      height: blockSizeVertical * 3,
                                    ),
                                    // USERNAME
                                    FormBuilderTextField(
                                        name: 'username',
                                        validator:
                                            FormBuilderValidators.required(
                                                errorText: usernameRequired),
                                        autofocus: false,
                                        style: const TextStyle(
                                            fontWeight: FontWeight.bold,
                                            color: Colors.black87),
                                        decoration:
                                            loginTextFieldStyle().copyWith()),
                                    SizedBox(
                                      height: blockSizeVertical * 1.5,
                                    ),
                                    // PASSWORD
                                    FormBuilderTextField(
                                      name: 'password',
                                      validator: FormBuilderValidators.required(
                                          errorText: passwordRequired),
                                      onChanged: (value) {
                                        value!.isEmpty
                                            ? setState(() {
                                                showSuffixIcon = false;
                                              })
                                            : setState(() {
                                                showSuffixIcon = true;
                                              });
                                      },
                                      autofocus: false,
                                      style: const TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.black87),
                                      decoration:
                                          loginTextFieldStyle().copyWith(
                                              suffixIcon: Visibility(
                                                visible: showSuffixIcon,
                                                child: _showPassword
                                                    ? IconButton(
                                                        icon: Icon(
                                                            FontAwesome5
                                                                .eye_slash,
                                                            size: 24,
                                                            color: Theme.of(
                                                                    context)
                                                                .textTheme
                                                                .displayLarge
                                                                ?.color),
                                                        onPressed: () {
                                                          setState(() {
                                                            _showPassword =
                                                                false;
                                                          });
                                                        },
                                                      )
                                                    : IconButton(
                                                        onPressed: () {
                                                          setState(() {
                                                            _showPassword =
                                                                true;
                                                          });
                                                        },
                                                        icon: Icon(
                                                            FontAwesome5.eye,
                                                            size: 24,
                                                            color: Theme.of(
                                                                    context)
                                                                .textTheme
                                                                .displayLarge
                                                                ?.color)),
                                              ),
                                              prefixIcon: const Icon(
                                                Icons.lock,
                                                color: primary,
                                              ),
                                              labelText: "Password",
                                              hintText: enterPassword),
                                      obscureText: _showPassword ? true : false,
                                    ),
                                    SizedBox(
                                      height: blockSizeVertical * 2,
                                    ),
                                    SizedBox(
                                      height: blockSizeVertical * 7,
                                      // Login Button
                                      child: SizedBox(
                                        width:
                                            MediaQuery.of(context).size.width,
                                        child: ElevatedButton(
                                          style: mainBtnStyle(
                                              second,
                                              Colors.transparent,
                                              Colors.white54),
                                          child: const Text(
                                            login,
                                            style:
                                                TextStyle(color: Colors.white),
                                          ),
                                          onPressed: () {
                                            final progress =
                                                ProgressHUD.of(context);

                                            FocusScope.of(context).unfocus();

                                            if (_formKey.currentState!
                                                .saveAndValidate()) {
                                              progress?.showWithText(
                                                'Logging in...',
                                              );

                                              BlocProvider.of<UserBloc>(context)
                                                  .add(UserLogin(
                                                username: "rjvincentlopeplopez",
                                                password: "shesthequ33n",
                                                // username: _formKey
                                                //     .currentState!
                                                //     .value['username'],
                                                // password: _formKey
                                                //     .currentState!
                                                //     .value['password'])
                                              ));
                                            }
                                          },
                                        ),
                                      ),
                                    ),
                                    SizedBox(
                                      height: blockSizeVertical * 1.5,
                                    ),

                                    SizedBox(
                                        height: blockSizeVertical * 7,
                                        child: SizedBox(
                                          width:
                                              MediaQuery.of(context).size.width,
                                          child: ElevatedButton.icon(
                                            style: mainBtnStyle(
                                                Colors.white,
                                                second,
                                                primary.withOpacity(.4)),
                                            icon: const Icon(
                                              Icons.qr_code,
                                              color: second,
                                            ),
                                            label: const Text(
                                              loginViaQr,
                                              style: TextStyle(color: second),
                                            ),
                                            onPressed: () {
                                              context
                                                  .read<UserBloc>()
                                                  .add(GetUuid());
                                            },
                                          ),
                                        )),
                                    SizedBox(
                                      height: blockSizeVertical * 1,
                                    ),
                                    const LoginViaQr(
                                        text: emergencyReponseLabel),
                                    SizedBox(
                                      height: blockSizeVertical * 1,
                                    ),
                                    // REQUEST SOS
                                    SizedBox(
                                      height: screenHeight * .07,
                                      width: MediaQuery.of(context).size.width,
                                      child: ElevatedButton.icon(
                                          icon: const Icon(
                                            FontAwesome5.life_ring,
                                            color: Colors.white,
                                          ),
                                          style: mainBtnStyle(
                                              third,
                                              Colors.transparent,
                                              Colors.white38),
                                          onPressed: () {},
                                          label: const Text(
                                            requestSOS,
                                            style:
                                                TextStyle(color: Colors.white),
                                          )),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                } else {
                  //New update available
                  return Update(
                    apkVersion: state.apkVersion!,
                    currenVersion: state.versionInfo!.version!,
                  );
                }
              });
            }
            if (state is UserError) {
              return SomethingWentWrong(
               message:onError ,
               onpressed:(){} ,
              );
            }
            if (state is InternetTimeout) {
              return const TimeOutError();
            }
            if (state is SplashScreen) {
              return const UniTSplashScreen();
            }
            return Container();
          }),
        ),
      ),
    );
  }
}
