import 'dart:ui';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'User.dart' as Users;
import 'package:http/http.dart' as http;
class WelcomePage extends StatefulWidget {
  const WelcomePage({Key? key}) : super(key: key);

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

class _WelcomePageState extends State<WelcomePage> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      body: Container(
          color: Colors.pink,
          child: Flex(
            direction: Axis.vertical,
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // Container(
              //     padding: EdgeInsets.all(20),
              //     alignment: Alignment.centerLeft,
              //     child: Text(
              //       'WELCOME',
              //       style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
              //       textAlign: TextAlign.left,
              //     )),
               Expanded(
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 100, vertical: 10),
                        child: Image(image: AssetImage('images/Launch.png')))),

              Container(
                  padding: EdgeInsets.all(20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text("Let's get started",
                          style: TextStyle(
                              fontSize: 30, fontWeight: FontWeight.bold)),
                      Divider(),
                      Text(
                          "Task Tracker is an App where you can track your daily activities, Analyze them and plan a better tomorrow.")
                    ],
                  )),
              Container(
                  padding: EdgeInsets.all(20),
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      InkWell(
                        child: Text(''),
                        // onTap: () {
                        //   Navigator.of(context).pushReplacementNamed('/');
                        // },
                      ),
                      ElevatedButton(
                          onPressed: () {
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (context) => const SignInPage()));
                          },
                          child: Text('Next', style: TextStyle(fontSize: 20)))
                    ],
                  ))
            ],
          )),
    ));
  }
}

class SignInPage extends StatefulWidget {
  const SignInPage({Key? key}) : super(key: key);

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

class _SignInPageState extends State<SignInPage> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
            body: Container(
                color: Colors.deepPurpleAccent,
                child: Flex(
                  direction: Axis.vertical,
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                        Expanded(
                          flex: 2,
                            child: Container(
                                padding: EdgeInsets.fromLTRB(0, 100, 0, 0),
                                height: 400,
                                child:
                                Image(image: AssetImage('images/signin.png'))),
                          ),
                      Expanded(

                        flex:1,
                          child: Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text("Sign in to stay connected",
                                    style: TextStyle(
                                        fontSize: 30,
                                        fontWeight: FontWeight.bold)),
                                Divider(),
                                Text(
                                    "Sign in and enjoy the flawless connection between all your devices. You can track your day from any device and keep it together.")
                              ],
                            ),
                          )),
                      Container(
                          padding: EdgeInsets.all(20),
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      primary: Colors.red),
                                  onPressed: () {
                                    Navigator.of(context).push(
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                const offlineLoginPage()));
                                  },
                                  child: Text('Use Offline',
                                      style: TextStyle(fontSize: 20))),
                              ElevatedButton(
                                  onPressed: () {
                                    Navigator.of(context).push(
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                const onlineLoginPage()));
                                  },
                                  child: Text('Next',
                                      style: TextStyle(fontSize: 20)))
                            ],
                          ))
                    ]))));
  }
}

class onlineLoginPage extends StatefulWidget {
  const onlineLoginPage({Key? key}) : super(key: key);

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

class _onlineLoginPageState extends State<onlineLoginPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();


  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 2);
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
            body: Container(
                color: Colors.purpleAccent,
                child: Flex(
                  direction: Axis.vertical,
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // Container(
                      //   padding: EdgeInsets.all(20),
                      //   alignment: Alignment.centerLeft,
                      //   child: Text(
                      //     'Sign in online',
                      //     style: TextStyle(
                      //         fontSize: 40, fontWeight: FontWeight.bold),
                      //     textAlign: TextAlign.left,
                      //   ),
                      // ),
                Expanded(

                        child: Container(
                            child:
                                Image(image: AssetImage('images/signin.png'))),
                      ),
                      Container(
                          padding: EdgeInsets.all(20),
                          child: Column(children: [
                            Container(
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(20),
                                    color: Colors.purple),
                                child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: TabBar(
                                      controller: _tabController,
                                      indicator: BoxDecoration(
                                          color: Colors.blueAccent,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      tabs: [
                                        TabItem('Our Account'),
                                        TabItem('OAuth')
                                      ],
                                    ))),
                            Divider(
                              height: 30,
                            ),
                            Container(
                              height: 320,
                              child: TabBarView(
                                controller: _tabController,
                                children: [
                                  Container(
                                      decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(10),
                                          color: Colors.purple),
                                      child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          mainAxisSize: MainAxisSize.max,
                                          children: [
                                            Container(
                                                alignment: Alignment.centerLeft,
                                                padding: EdgeInsets.fromLTRB(
                                                    10, 10, 10, 0),
                                                child: Text(
                                                  'Username',
                                                  style:
                                                      TextStyle(fontSize: 16),
                                                )),
                                            Expanded(
                                                  child: Container(
                                                    padding: EdgeInsets.all(15),
                                                    child: TextField(
                                                      controller: usernameController,
                                                      autocorrect: false,
                                                      style: TextStyle(
                                                        color: Colors.black,
                                                      ),
                                                      decoration: InputDecoration(
                                                        hintText: 'Username',
                                                          filled: true,
                                                          fillColor:
                                                              Colors.white,
                                                          border: OutlineInputBorder(
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .circular(
                                                                          10))),
                                                    ),
                                                  ),
                                                ),
                                            Container(
                                                alignment: Alignment.centerLeft,
                                                padding: EdgeInsets.fromLTRB(
                                                    10, 10, 10, 0),
                                                child: Text(
                                                  'Password',
                                                  style:
                                                      TextStyle(fontSize: 16),
                                                )),
                                             Expanded(
                                                  child: Container(
                                                    padding: EdgeInsets.all(15),
                                                    child: TextField(
                                                      controller: passwordController,
                                                      obscureText: true,
                                                      autocorrect: false,
                                                      enableSuggestions: false,
                                                      style: TextStyle(
                                                        fontWeight:
                                                            FontWeight.bold,
                                                        color: Colors.black,
                                                      ),
                                                      decoration: InputDecoration(
                                                        hintText: 'Password',
                                                          filled: true,
                                                          fillColor:
                                                              Colors.white,
                                                          border: OutlineInputBorder(
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .circular(
                                                                          10))),
                                                    ),
                                                  ),
                                                ),
                                            Container(
                                                width: 200,
                                                padding: EdgeInsets.all(20),
                                                child: ElevatedButton(
                                                    style: ElevatedButton
                                                        .styleFrom(
                                                            primary:
                                                                Colors.green),
                                                    onPressed: () {
                                                      login();
                                                    },
                                                    child: Text(
                                                      'Login',
                                                      style: TextStyle(
                                                          fontSize: 20),
                                                    )))
                                          ])),
                                  Container(
                                      decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(10),
                                          color: Colors.purple),
                                      child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          mainAxisSize: MainAxisSize.max,
                                          children: [
                                            Container(
                                              height: 50,
                                              child: ElevatedButton(
                                                style: ElevatedButton.styleFrom(
                                                  primary: Colors.green,
                                                ),
                                                  onPressed: (){}, child: Row(
                                                mainAxisSize: MainAxisSize.min,
                                                children: [
                                                Icon(Icons.android),
                                                SizedBox(width: 20,),
                                                Text("Sign with Google", style: TextStyle(fontSize: 20))
                                              ],)),
                                            ),
                                            Divider(height: 50,),
                                            Container(
                                              padding: EdgeInsets.all(50),
                                              child:Text("New OAuth Sign in methods are on the way...")
                                            )

                                          ]))
                                ],
                              ),
                            )
                          ])),
                      Container(
                          padding: EdgeInsets.all(20),
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      primary: Colors.red),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: Text('Back',
                                      style: TextStyle(fontSize: 20))),
                              SizedBox()
                            ],
                          ))
                    ]))));
  }

  Widget TabItem(String text) {
    return Text(text, style: TextStyle(fontSize: 20, color: Colors.white));
  }

  Future<void> login() async {
    if(usernameController.text.length < 3 || passwordController.text.length < 3){
      showAlertDialog(context, "Failed", "Please enter a valid username and password");
      return;
    }

    http.Response loginResponse = await Users.login(usernameController.text, passwordController.text);
    print(loginResponse.body);
    if(loginResponse.body.toLowerCase().contains("success")){
      final prefs = await SharedPreferences.getInstance();
      prefs.setString("username", usernameController.text);
      prefs.setString("password", passwordController.text);
      Navigator.of(context).pushNamedAndRemoveUntil('/', (route) => false);
    }else{
      showAlertDialog(context, "Failed to login", "There was an error trying to authorize you in servers.");
    }
  }
}
showAlertDialog(BuildContext context, String title, String message) {

  // set up the button
  Widget okButton = TextButton(
    child: Text("OK"),
    onPressed: () { Navigator.of(context).pop(); },
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text(title),
    content: Text(message),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

class offlineLoginPage extends StatefulWidget {
  const offlineLoginPage({Key? key}) : super(key: key);

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

class _offlineLoginPageState extends State<offlineLoginPage> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
            body: Container(
                color: Colors.deepOrange,
                child: Flex(
                  direction: Axis.vertical,
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // Container(
                      //     padding: EdgeInsets.all(20),
                      //     alignment: Alignment.centerLeft,
                      //     child: Text(
                      //       'Offline Mode',
                      //       style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
                      //       textAlign: TextAlign.left,
                      //     )),
                      Expanded(
                            child: Container(
                                height: 400,
                                child: Image(
                                    image: AssetImage('images/offline.png'))),
                      ),
                      Container(
                          padding: EdgeInsets.all(20),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Divider(
                                height: 30,
                              ),
                              Text("Enter your name to continue",
                                  style: TextStyle(
                                      fontSize: 30,
                                      fontWeight: FontWeight.bold)),
                              SizedBox(
                                height: 30,
                              ),
                              TextField(
                                decoration: InputDecoration(
                                    hintText: 'ex: John doe',
                                    focusColor: Colors.white,
                                    border: OutlineInputBorder()),
                              ),
                              Divider(
                                height: 30,
                              ),
                              Text(
                                  'Note: \nYou cannot use seemless multiple devices support with offline mode. \nYou can sign to online account anytime in settings page')
                            ],
                          )),
                      Container(
                          padding: EdgeInsets.all(20),
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      primary: Colors.green),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: Text('Sign online',
                                      style: TextStyle(fontSize: 20))),
                              ElevatedButton(
                                  onPressed: () {
                                    Navigator.of(context).push(
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                const SignInPage()));
                                  },
                                  child: Text('Continue',
                                      style: TextStyle(fontSize: 20)))
                            ],
                          ))
                    ]))));
  }
}
