import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:permission_handler/permission_handler.dart';
import '../classes/auth_service.dart';
import '../pages/ListItemMenu.dart';
import '../pages/AddProfile.dart';
import '../pages/ForgotPassword.dart';
import '../classes/alert.dart';
import '../classes/ad_helper.dart';

class LoginDemo extends StatefulWidget {
  @override
  _LoginDemoState createState() => _LoginDemoState();
}

class _LoginDemoState extends State<LoginDemo> with ShowAlertDialog {
  BannerAd? _bannerAd;
  TextEditingController inputPseudo = TextEditingController();
  TextEditingController inputPassword = TextEditingController();
  final AuthService _authService = AuthService();
  bool _rememberMe = false;

  Future<void> _login(BuildContext context) async {
    final pseudo = inputPseudo.text;
    final password = inputPassword.text;

    if (pseudo.isEmpty || password.isEmpty) {
      showAlertDialog(context, "Erreur", "Champ vide");
      return;
    }

    bool success =
        await _authService.login(pseudo, password, rememberMe: _rememberMe);

    if (success) {
      Navigator.push(
          context, MaterialPageRoute(builder: (_) => ListItemMenu()));
    } else {
      showAlertDialog(context, "Erreur", "Échec de l'authentification");
    }
  }

  @override
  void initState() {
    super.initState();
    AdHelper.createBannerAd(() => setState(() {})).then((ad) {
      setState(() {
        _bannerAd = ad;
      });
    });

    _checkLocationPermission();
    _checkLoginStatus();
  }

  Future<void> _checkLoginStatus() async {
    bool loggedIn = await _authService.isLoggedIn();
    if (loggedIn) {
      Navigator.push(
          context, MaterialPageRoute(builder: (_) => ListItemMenu()));
    }
  }

  Future<void> _checkLocationPermission() async {
    PermissionStatus status = await Permission.location.status;
    if (!status.isGranted) {
      await Permission.location.request();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("Login Page"),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            _bannerAd == null
                ? SizedBox.shrink()
                : SizedBox(
                    height: _bannerAd!.size.height.toDouble(),
                    width: _bannerAd!.size.width.toDouble(),
                    child: AdWidget(ad: _bannerAd!),
                  ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: TextField(
                controller: inputPseudo,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Pseudo',
                  hintText: 'Enter pseudo existant',
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
              child: TextField(
                controller: inputPassword,
                obscureText: true,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Password',
                  hintText: 'Enter secure password',
                ),
              ),
            ),
            CheckboxListTile(
              title: Text("Se souvenir de moi"),
              value: _rememberMe,
              onChanged: (newValue) {
                setState(() {
                  _rememberMe = newValue ?? false;
                });
              },
            ),
            TextButton(
              onPressed: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (_) => PasswordForgot()));
              },
              child: Text('Forgot Password',
                  style: TextStyle(color: Colors.blue, fontSize: 15)),
            ),
            Container(
              height: 50,
              width: 250,
              decoration: BoxDecoration(
                  color: Colors.blue, borderRadius: BorderRadius.circular(20)),
              child: TextButton(
                onPressed: () => _login(context),
                child: Text('Login',
                    style: TextStyle(color: Colors.white, fontSize: 25)),
              ),
            ),
            SizedBox(height: 130),
            InkWell(
              child: Text('New User? Create Account'),
              onTap: () {
                Navigator.push(
                    context, MaterialPageRoute(builder: (_) => AddProfile()));
              },
            ),
          ],
        ),
      ),
    );
  }
}