import 'dart:io';

import 'package:aitrainer_app/bloc/account/account_bloc.dart';
import 'package:aitrainer_app/bloc/login/login_bloc.dart';
import 'package:aitrainer_app/repository/customer_repository.dart';
import 'package:aitrainer_app/repository/training_plan_repository.dart';
import 'package:aitrainer_app/repository/user_repository.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar_min.dart';
import 'package:aitrainer_app/widgets/dialog_common.dart';
import 'package:aitrainer_app/widgets/dialog_web_browser.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

import '../library_keys.dart';

// ignore: must_be_immutable
class RegistrationPage extends StatelessWidget with Trans {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    final accountBloc = BlocProvider.of<AccountBloc>(context);

    CustomerRepository? customerRepository;
    if (ModalRoute.of(context) != null && ModalRoute.of(context)!.settings.arguments != null) {
      customerRepository = ModalRoute.of(context)!.settings.arguments as CustomerRepository;
      print("CustomerFitness reg ${customerRepository.customer!.toJson()}");
    }

    setContext(context);
    return Scaffold(
        appBar: AppBarMin(),
        body: BlocProvider(
            create: (context) => LoginBloc(
                userRepository: UserRepository(),
                accountBloc: accountBloc,
                context: context,
                isRegistration: true,
                customerRepository: customerRepository),
            child: BlocConsumer<LoginBloc, LoginState>(listener: (context, state) {
              if (state is LoginError) {
                ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(backgroundColor: Colors.orange, content: Text(t(state.message), style: TextStyle(color: Colors.white))));
              } else if (state is LoginSuccess) {
                TrainingPlanRepository trainingPlanRepository = TrainingPlanRepository();
                showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return DialogCommon(
                        title: t("Successful Registration"),
                        descriptions: t("Based on your initial data, we will generate the personalized training plan for you."),
                        text: "OK",
                        onTap: () => {Navigator.of(context).popAndPushNamed('customerWelcomePage')},
                        onCancel: () => {
                          trainingPlanRepository.generateTrainingPlan(),
                          Navigator.of(context).popAndPushNamed("customerWelcomePage"),
                        },
                      );
                    });
              } else if (state is LoginSkipped) {
                showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return DialogCommon(
                        title: t("No Registration"),
                        descriptions: t("You will skip the registration process."),
                        description2: t("Please take a short tour in the app"),
                        text: "OK",
                        onTap: () => {Navigator.of(context).pushNamed('home')},
                        onCancel: () => {
                          Navigator.of(context).pop(),
                        },
                      );
                    });
              }
            }, builder: (context, state) {
              final loginBloc = BlocProvider.of<LoginBloc>(context);
              if (customerRepository != null) {
                print("Customer data ${customerRepository.customer!.toJson()}");
              }
              return ModalProgressHUD(
                child: loadForm(loginBloc, accountBloc),
                inAsyncCall: state is LoginLoading,
                opacity: 0.5,
                color: Colors.black54,
                progressIndicator: CircularProgressIndicator(),
              );
            })));
  }

  Widget loadForm(LoginBloc loginBloc, AccountBloc accountBloc) {
    return SafeArea(
      top: false,
      bottom: false,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('asset/image/WT_menu_dark.jpg'),
            fit: BoxFit.cover,
            alignment: Alignment.center,
          ),
        ),
        child: buildLoginForm(loginBloc, accountBloc),
      ),
    );
  }

  Widget buildLoginForm(LoginBloc loginBloc, AccountBloc accountBloc) {
    return Form(
      key: _scaffoldKey,
      child: Container(
          padding: const EdgeInsets.only(left: 20, right: 20),
          child: ListView(shrinkWrap: false, padding: EdgeInsets.only(top: 10.0), children: <Widget>[
            SizedBox(
              height: 100,
            ),
            ListTile(
                title: Text(
              t("SignUp"),
              style: GoogleFonts.inter(
                color: Colors.white,
                fontWeight: FontWeight.w500,
                shadows: <Shadow>[
                  Shadow(
                    offset: Offset(3.0, 3.0),
                    blurRadius: 6.0,
                    color: Colors.black54,
                  ),
                  Shadow(
                    offset: Offset(-3.0, 3.0),
                    blurRadius: 6.0,
                    color: Colors.black54,
                  ),
                ],
              ),
            )),
            SizedBox(
              height: 20,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextButton(
                  child: Image.asset(
                    'asset/image/button_fb.png',
                    width: 60,
                  ),
                  onPressed: () => {loginBloc.add(RegistrationFB())},
                ),
                Platform.isAndroid
                    ? TextButton(
                        child: Image.asset(
                          'asset/image/button_google.png',
                          width: 60,
                        ),
                        onPressed: () => {loginBloc.add(RegistrationGoogle())},
                      )
                    : Offstage(),
                Platform.isIOS
                    ? TextButton(
                        child: Image.asset(
                          'asset/image/button_apple.png',
                          width: 60,
                        ),
                        onPressed: () => {loginBloc.add(RegistrationApple())},
                      )
                    : Offstage(),
              ],
            ),
            Divider(
              color: Colors.transparent,
            ),
            TextFormField(
              key: LibraryKeys.loginEmailField,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.only(left: 15, top: 15, bottom: 15),
                labelText: t('Email'),
                labelStyle: TextStyle(
                  fontSize: 14,
                  color: Color(0xffb4f500),
                ),
                fillColor: Colors.white24,
                filled: true,
                border: OutlineInputBorder(
                  gapPadding: 4.0,
                  borderRadius: BorderRadius.circular(12.0),
                  borderSide: BorderSide(color: Colors.green[50]!, width: 0.4),
                ),
              ),
              initialValue: loginBloc.userRepository.user.email,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              validator: (val) {
                final String? validator = loginBloc.emailValidation(val!);
                return validator == null ? null : t(validator);
              },
              onChanged: (value) => loginBloc.add(LoginEmailChange(email: value)),
              keyboardType: TextInputType.emailAddress,
              style: new TextStyle(fontSize: 16, color: Colors.white),
            ),
            Divider(
              color: Colors.transparent,
            ),
            TextFormField(
              key: LibraryKeys.loginPasswordField,
              obscureText: loginBloc.obscure,
              decoration: InputDecoration(
                labelStyle: TextStyle(
                  fontSize: 14,
                  color: Color(0xffb4f500),
                ),
                contentPadding: EdgeInsets.only(left: 15, top: 15, bottom: 15),
                suffixIcon: IconButton(
                  onPressed: () => {loginBloc.add(LoginPasswordChangeObscure())},
                  icon: Icon(Icons.remove_red_eye),
                ),
                labelText: t('Password'),
                fillColor: Colors.white24,
                filled: true,
                border: OutlineInputBorder(
                  gapPadding: 1.0,
                  borderRadius: BorderRadius.circular(12.0),
                  borderSide: BorderSide(color: Colors.green[50]!, width: 0.4),
                ),
              ),
              initialValue: loginBloc.userRepository.user.password,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              validator: (val) {
                final String? validator = loginBloc.passwordValidation(val!);
                return validator == null ? null : t(validator);
              },
              onChanged: (value) => loginBloc.add(LoginPasswordChange(password: value)),
              keyboardType: TextInputType.visiblePassword,
              style: new TextStyle(fontSize: 16, color: Colors.white),
            ),
            Divider(
              color: Colors.transparent,
            ),
            // getDataProtection(loginBloc),
            // loginBloc.emailCheckbox ? getEmailSubscription(loginBloc) : Offstage(),
            Divider(
              color: Colors.transparent,
            ),
            ListTile(
              leading: Icon(
                Icons.check,
                color: Colors.green,
              ),
              title: Text(
                t("With the registration I accept the data policy and the terms of use."),
                style: GoogleFonts.inter(
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  shadows: <Shadow>[
                    Shadow(
                      offset: Offset(3.0, 3.0),
                      blurRadius: 6.0,
                      color: Colors.black54,
                    ),
                    Shadow(
                      offset: Offset(-3.0, 3.0),
                      blurRadius: 6.0,
                      color: Colors.black54,
                    ),
                  ],
                ),
              ),
            ),
            Row(mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[
              TextButton(
                  key: LibraryKeys.loginOKButton,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Image.asset('asset/icon/gomb_zold_a.png', width: 140, height: 60),
                      Text(
                        t("OK"),
                        style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.white),
                      ),
                    ],
                  ),
                  onPressed: () => {loginBloc.add(RegistrationSubmit())}),
            ]),
            Divider(
              color: Colors.transparent,
            ),
            Divider(
              color: Colors.transparent,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[
              InkWell(
                child: Text(
                  t('Login'),
                  style: GoogleFonts.inter(
                    decoration: TextDecoration.underline,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                    shadows: <Shadow>[
                      Shadow(
                        offset: Offset(3.0, 3.0),
                        blurRadius: 6.0,
                        color: Colors.black54,
                      ),
                      Shadow(
                        offset: Offset(-3.0, 3.0),
                        blurRadius: 6.0,
                        color: Colors.black54,
                      ),
                    ],
                  ),
                ),
                onTap: () => Navigator.of(context).pushNamed('login'),
              ),
              Spacer(flex: 1),
              InkWell(
                  child: Text(
                    t('Terms Of Use'),
                    style: GoogleFonts.inter(
                      decoration: TextDecoration.underline,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                      shadows: <Shadow>[
                        Shadow(
                          offset: Offset(3.0, 3.0),
                          blurRadius: 6.0,
                          color: Colors.black54,
                        ),
                        Shadow(
                          offset: Offset(-3.0, 3.0),
                          blurRadius: 6.0,
                          color: Colors.black54,
                        ),
                      ],
                    ),
                  ),
                  onTap: () => {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return DialogWebBrowser(url: 'https://workouttest.com/terms-of-use/', javascriptEnabled: true);
                            })
                      }),
              Spacer(flex: 1),
              InkWell(
                  child: Text(
                    t('Privacy'),
                    style: GoogleFonts.inter(
                      decoration: TextDecoration.underline,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                      shadows: <Shadow>[
                        Shadow(
                          offset: Offset(2.0, 2.0),
                          blurRadius: 10.0,
                          color: Colors.black87,
                        ),
                      ],
                    ),
                  ),
                  onTap: () => {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return DialogWebBrowser(url: 'https://workouttest.com/privacy/', javascriptEnabled: true);
                            })
                      }),
            ]),
          ])),
    );
  }
}