import 'dart:convert';

import 'package:easycook_mobile/pages/auth/lupa_kata_sandi.dart';
import 'package:easycook_mobile/pages/auth/register.dart';
import 'package:easycook_mobile/pages/home.dart';
import 'package:easycook_mobile/shared/shared_values.dart';
import 'package:easycook_mobile/theme.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  TextEditingController emailController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  void loginWithEmail() async {
    print("runn");
    var headers = {'Content-Type': 'application/json'};

    var url = Uri.parse(BASE_URL + "/accounts/login/");

    Map body = {
      'username': emailController.text,
      'password': passwordController.text
    };

    print(body);

    http.Response response =
        await http.post(url, body: jsonEncode(body), headers: headers);
    print(url);

    print(jsonEncode(body));
    print(response.statusCode);
    print(response.body);

    if (response.statusCode == 200) {
      final json = jsonDecode(response.body);
      print(json['token']);
      var token = json['token'];

      final SharedPreferences? prefs = await _prefs;
      await prefs?.setString('token', token);
      Navigator.of(context).push(
          MaterialPageRoute(builder: (BuildContext context) => HomePage()));
    }
  }

  getPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var token = prefs.getString('token');
    print("wowowowo");
    print(token);
    if (token != null) {
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => HomePage()));
    } else {
      // Navigator.pushReplacement(-
      //     context, MaterialPageRoute(builder: (context) => Menu()));
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getPrefs();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        padding: EdgeInsets.all(16),
        child: ListView(
          children: <Widget>[
            Center(
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 110),
                    child: Container(
                      child: SizedBox(
                        height: 65,
                        width: 239,
                        child: Image.asset('images/Logo.png'),
                      ),
                    ),
                  ),
                  Row(
                    children: [
                      _titleDesc(),
                    ],
                  ),
                  _textField(context, emailController, passwordController),
                  _buildButton(context, loginWithEmail),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Widget _titleDesc() {
  return Column(
    children: <Widget>[
      Padding(
        padding: EdgeInsets.only(top: 32),
      ),
      Text(
        "Masuk ke Akun Anda",
        style: GoogleFonts.montserrat().copyWith(
          color: Colors.black,
          fontWeight: FontWeight.bold,
          fontSize: 24,
        ),
      ),
      Padding(
        padding: EdgeInsets.only(top: 12.0),
      ),
    ],
  );
}

Widget _textField(BuildContext context, TextEditingController emailController,
    TextEditingController passwordController) {
  return Column(
    children: <Widget>[
      Padding(
        padding: EdgeInsets.only(top: 12.0),
      ),
      Row(
        children: [
          Text(
            'Username',
            style: GoogleFonts.montserrat().copyWith(
              color: Colors.black,
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
        ],
      ),
      Padding(
        padding: EdgeInsets.only(top: 5),
      ),
      TextFormField(
        controller: emailController,
        decoration: const InputDecoration(
          border: OutlineInputBorder(),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.black,
              width: 1.5,
            ),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.blueAccent,
              width: 3.0,
            ),
          ),
          hintText: "Username",
          hintStyle: TextStyle(color: Colors.black26),
        ),
        style: TextStyle(color: Colors.black),
        autofocus: false,
      ),
      Padding(
        padding: EdgeInsets.only(top: 30),
      ),
      Row(
        children: [
          Text(
            'Password',
            style: GoogleFonts.montserrat().copyWith(
              color: Colors.black,
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
        ],
      ),
      Padding(
        padding: EdgeInsets.only(top: 5),
      ),
      TextFormField(
        controller: passwordController,
        decoration: const InputDecoration(
          border: OutlineInputBorder(),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.black,
              width: 1.5,
            ),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.blueAccent,
              width: 3.0,
            ),
          ),
          hintText: "Password",
          hintStyle: TextStyle(color: Colors.black26),
        ),
        style: TextStyle(color: Colors.black),
        obscureText: true,
        autofocus: false,
      ),
      Row(
        children: [
          SizedBox(
            width: 220,
          ),
          TextButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => LupaSandiPage(),
                ),
              );
            },
            child: Text(
              'Lupa Password?',
              style: GoogleFonts.montserrat(),
            ),
          ),
        ],
      ),
    ],
  );
}

Widget _buildButton(BuildContext context, void Function() loginWithEmail) {
  return Column(
    children: [
      SizedBox(
        height: 48,
        width: 328,
        child: TextButton(
          style: TextButton.styleFrom(
            backgroundColor: Colors.amber,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20),
            ),
          ),
          onPressed: () {
            loginWithEmail();
          },
          child: Text(
            'Masuk',
            style: GoogleFonts.montserrat().copyWith(
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
      Padding(
        padding: EdgeInsets.only(top: 10.0),
      ),
      Column(
        children: [
          Row(
            children: [
              SizedBox(
                width: 45,
              ),
              Text(
                'Belum punya akun?',
                style: GoogleFonts.montserrat().copyWith(
                  color: Colors.black,
                ),
              ),
              TextButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => RegisterPage(),
                    ),
                  );
                },
                child: Text(
                  'Daftar Sekarang',
                  style: GoogleFonts.montserrat().copyWith(
                    color: Colors.amber,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    ],
  );
}
