import 'package:another_flushbar/flushbar.dart';
import 'package:easycook_mobile/blocs/register/register_cubit.dart';
import 'package:easycook_mobile/pages/auth/login.dart';
import 'package:easycook_mobile/pages/personalisasi/favorite_cuisine.dart';
import 'package:flutter/material.dart';
import 'package:easycook_mobile/theme.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:google_fonts/google_fonts.dart';

class RegisterPage extends StatefulWidget {
  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  late RegisterCubit _registerCubit;

  TextEditingController _firstnameCtrl = TextEditingController();
  TextEditingController _lastnameCtrl = TextEditingController();
  TextEditingController _usernameCtrl = TextEditingController();
  TextEditingController _emailCtrl = TextEditingController();
  TextEditingController _passwordCtrl = TextEditingController();
  TextEditingController _passwordconfirmCtrl = TextEditingController();
  TextEditingController _phoneCtrl = TextEditingController();
  TextEditingController searchController = TextEditingController();
  TextEditingController searchController2 = TextEditingController();

  String password = '';
  String confirmPassword = '';
  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    _registerCubit = RegisterCubit();
    super.initState();
  }

  @override
  void dispose() {
    _registerCubit.close();
    super.dispose();
  }

  Widget testField(String title, TextEditingController textEditingController,
      bool obscureText) {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.only(top: 12.0),
        ),
        Row(
          children: [
            Text(
              title,
              style: GoogleFonts.montserrat().copyWith(
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
            ),
          ],
        ),
        Padding(
          padding: EdgeInsets.only(top: 5),
        ),
        TextFormField(
          obscureText: obscureText,
          controller: textEditingController,
          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,
              ),
            ),
          ),
          style: TextStyle(color: Colors.black),
          autofocus: false,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Kolom harus diisi!!!';
            }
            return null;
          },
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => _registerCubit,
      child: BlocListener(
        bloc: _registerCubit,
        listener: (context, state) {
          if (state is RegisterSuccess) {
            Flushbar(
              title: "Success",
              message: "Register berhasil silahkan Login",
              duration: Duration(seconds: 3),
            )..show(context);
          }
          if (state is RegisterLoading) {
            Flushbar(
              title: "Loading",
              message: "Mohon tunggu sebentar, akun anda sedang didaftarkan",
              duration: Duration(seconds: 3),
            )..show(context);
          }
          if (state is RegisterFailure) {
            Flushbar(
              title: "Error",
              message: state.message,
              duration: Duration(seconds: 3),
            )..show(context);
          }
        },
        child: Scaffold(
          body: Container(
            child: Padding(
              padding: EdgeInsets.all(16),
              child: ListView(
                children: [
                  Padding(
                    padding: const EdgeInsets.only(top: 110),
                    child: Container(
                      child: SizedBox(
                        height: 65,
                        width: 239,
                        child: Image.asset('images/Logo.png'),
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: _titleDesc(),
                  ),
                  Form(
                    key: _formKey,
                    child: Column(
                      children: <Widget>[
                        testField("Nama Depan", _firstnameCtrl, false),
                        testField("Nama Belakang", _lastnameCtrl, false),
                        testField("Username", _usernameCtrl, false),
                        testField("Email", _emailCtrl, false),
                        testField("No Telp", _phoneCtrl, false),
                        Column(
                          children: [
                            Padding(
                              padding: EdgeInsets.only(top: 12.0),
                            ),
                            Row(
                              children: [
                                Text(
                                  'Password',
                                  style: GoogleFonts.montserrat().copyWith(
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16,
                                  ),
                                ),
                              ],
                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 5),
                            ),
                            TextFormField(
                              obscureText: true,
                              controller: _passwordCtrl,
                              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: "",
                                hintStyle: TextStyle(color: Colors.black26),
                              ),
                              style: TextStyle(color: Colors.black),
                              autofocus: false,
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return 'Kolom harus diisi!!!';
                                }
                                return null;
                              },
                              onChanged: (value) {
                                setState(() {
                                  password = value;
                                });
                              },
                            ),
                          ],
                        ),
                        Column(
                          children: [
                            Padding(
                              padding: EdgeInsets.only(top: 12.0),
                            ),
                            Row(
                              children: [
                                Text(
                                  'Konfirmasi Password',
                                  style: GoogleFonts.montserrat().copyWith(
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16,
                                  ),
                                ),
                              ],
                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 5),
                            ),
                            TextFormField(
                              obscureText: true,
                              controller: _passwordconfirmCtrl,
                              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: "",
                                hintStyle: TextStyle(color: Colors.black26),
                              ),
                              style: TextStyle(color: Colors.black),
                              autofocus: false,
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return 'Kolom harus diisi!!!';
                                }
                                return null;
                              },
                              onChanged: (value) {
                                setState(() {
                                  confirmPassword = value;
                                });
                              },
                            ),
                          ],
                        ),
                        _buildButton(context, () {
                          if (_formKey.currentState!.validate()) {
                            if (password != confirmPassword) {
                              Flushbar(
                                title: "Error",
                                message: "Password tidak cocok!!!",
                                duration: Duration(seconds: 3),
                              )..show(context);
                            } else {
                              _registerCubit.register(
                                firstName: _firstnameCtrl.text,
                                lastName: _lastnameCtrl.text,
                                username: _usernameCtrl.text,
                                email: _emailCtrl.text,
                                password: _passwordCtrl.text,
                                phone: _phoneCtrl.text,
                              );
                            }
                          } else {
                            Flushbar(
                              title: "Error",
                              message: "Kolom tidak boleh kosong",
                              duration: Duration(seconds: 3),
                            )..show(context);
                          }
                        }),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

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

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