import 'dart:io';

//import 'package:firebase_auth/firebase_auth.dart' as auth;
//import 'package:flutter/cupertino.dart';
import 'package:adaptive_action_sheet/adaptive_action_sheet.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jubo/control/personService.dart';
import 'package:jubo/main.dart';
import 'package:jubo/model/person.dart';
import 'package:jubo/preLogin.dart';
import 'package:jubo/ui/loading.dart';
import 'package:jubo/ui/settings.dart';
import 'package:jubo/control/authService.dart';
import 'package:jubo/ui/sucess.dart';
import '../util/params.dart';
import 'package:intl/intl.dart';
//import 'package:flutter_login_screen/main.dart';
//import 'package:flutter_login_screen/model/user.dart';
//import 'package:flutter_login_screen/services/authenticate.dart';
import '../util/helper.dart';
//import 'package:flutter_login_screen/ui/home/homeScreen.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:image/image.dart' as ImageProcess;

File _image;
Image current;
ModelPerson loggedPerson;

class Profile extends StatefulWidget {
  Profile();

  @override
  State createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  final ImagePicker _imagePicker = ImagePicker();
  TextEditingController _passwordController = new TextEditingController();
  GlobalKey<FormState> _key = new GlobalKey();
  AutovalidateMode _validate = AutovalidateMode.disabled;
  String name,
      email,
      birth,
      birthSql,
      password,
      confirmPassword,
      type,
      photo,
      inserted_date;
  int id;
  bool loading = false;
  bool sucess = false;

  @override
  void initState() {
    loadPerson();
    super.initState();
  }

  void loadPerson() async {
    setState(() => loading = true);
    AuthenticationService auth = new AuthenticationService();
    await Future.delayed(Duration(seconds: 1));
    loggedPerson = await auth.getPerson();
    //Image c = await auth.getPhoto();
    setState(() {
      /*current = Image.asset(
        'assets/images/photo_1.jb',
        fit: BoxFit.cover,
      );*/
      print("$urlPrincipal/ws_jubo/service/v1/person/photo/${loggedPerson.id}");
      current = Image(
          image: NetworkImage(
              "$urlPrincipal/ws_jubo/service/v1/person/photo/${loggedPerson.id}"));
      id = loggedPerson.id;
      password = loggedPerson.password;
      photo = loggedPerson.photo;
      name = loggedPerson.name;
      email = loggedPerson.email;
      inserted_date = loggedPerson.inserted_date;
      type = loggedPerson.type;
      birth = loggedPerson.birth;
      birthSql =
          DateFormat('yyyy-MM-dd').format(DateTime.parse((loggedPerson.birth)));
      birthController.text =
          DateFormat('dd/MM/yyyy').format(DateTime.parse((loggedPerson.birth)));
      //current = c;
      loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    /**if (Platform.isAndroid) {
      retrieveLostData();
    }
**/

    return loading
        ? Loading()
        : sucess
            ? Sucess()
            : Scaffold(
                appBar: AppBar(
                  elevation: 5.0,
                  backgroundColor: COLOR_PRIMARY,
                  title: Text("Meus Dados"),
                  leading: TextButton(
                    child: Icon(
                      Icons.arrow_back,
                      size: 30.0,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ),
                body: SingleChildScrollView(
                  child: new Container(
                    margin:
                        new EdgeInsets.only(left: 16.0, right: 16, bottom: 16),
                    child: new Form(
                      key: _key,
                      autovalidateMode: _validate,
                      child: formUI(),
                    ),
                  ),
                ),
              );
  }

  /*Future<void> retrieveLostData() async {
    final LostData response = await _imagePicker.getLostData();
    if (response == null) {
      return;
    }
    if (response.file != null) {
      setState(() {
        _image = File(response.file.path);
      });
    }
  }*/

  _onCameraClick() {
    showAdaptiveActionSheet(
      context: context,
      title: Text(
        "Adicionar foto de perfil",
        style: TextStyle(fontSize: 15.0),
      ),
      actions: <BottomSheetAction>[
        BottomSheetAction(
          title: Text("Galeria"),
          onPressed: () async {
            Navigator.pop(context);
            PickedFile image = await _imagePicker.getImage(
              source: ImageSource.gallery,
              imageQuality: 80,
              maxHeight: 500,
              maxWidth: 500,
            );
            if (image != null)
              setState(() {
                _image = File(image.path);
              });
          },
        ),
        BottomSheetAction(
          title: Text("Câmera"),
          onPressed: () async {
            Navigator.pop(context);
            PickedFile image = await _imagePicker.getImage(
              source: ImageSource.camera,
              imageQuality: 80,
              maxHeight: 500,
              maxWidth: 500,
            );
            if (image != null)
              setState(() {
                _image = File(image.path);
              });
          },
        )
      ],
      cancelAction: CancelAction(
        title: Text("Cancelar"),
        /*onPressed: () {
          Navigator.pop(context);
        },*/
      ),
    );
  }

  Widget formUI() {
    return new Column(
      children: <Widget>[
        Padding(
          padding:
              const EdgeInsets.only(left: 8.0, top: 32, right: 8, bottom: 8),
          child: Stack(
            alignment: Alignment.bottomCenter,
            children: <Widget>[
              CircleAvatar(
                radius: 65,
                backgroundColor: Colors.grey.shade400,
                child: ClipOval(
                  child: SizedBox(
                    width: 170,
                    height: 170,
                    child: _image != null
                        ? Image.file(
                            _image,
                            fit: BoxFit.cover,
                          )
                        : current != null
                            ? current
                            : Image.asset(
                                'assets/images/placeholder.jpg',
                                fit: BoxFit.cover,
                              ),
                  ),
                ),
              ),
              Positioned(
                left: 80,
                right: 0,
                child: FloatingActionButton(
                    backgroundColor: COLOR_PRIMARY,
                    child: Icon(Icons.camera_alt),
                    mini: true,
                    onPressed: _onCameraClick),
              )
            ],
          ),
        ),
        ConstrainedBox(
            constraints: BoxConstraints(minWidth: double.infinity),
            child: Padding(
                padding:
                    const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
                child: TextFormField(
                    initialValue: this.name,
                    validator: validateName,
                    onSaved: (String val) {
                      this.name = val;
                    },
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        hintText: 'Primeiro nome',
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0),
                            borderSide:
                                BorderSide(color: COLOR_PRIMARY, width: 2.0)),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ))))),
        ConstrainedBox(
            constraints: BoxConstraints(minWidth: double.infinity),
            child: Padding(
                padding:
                    const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
                child: TextFormField(
                    initialValue: email,
                    keyboardType: TextInputType.emailAddress,
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    validator: validateEmail,
                    onSaved: (String val) {
                      email = val;
                    },
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        hintText: 'Email',
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0),
                            borderSide:
                                BorderSide(color: COLOR_PRIMARY, width: 2.0)),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ))))),
        ConstrainedBox(
            constraints: BoxConstraints(minWidth: double.infinity),
            child: Padding(
                padding:
                    const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
                child: TextFormField(
                    validator: validateDate,
                    onSaved: (String val) {
                      birth = val;
                    },
                    controller: birthController,
                    onTap: () {
                      _selectDate();
                      FocusScope.of(context).requestFocus(new FocusNode());
                    },
                    readOnly: true,
                    keyboardType: TextInputType.datetime,
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        hintText: 'Data de Nascimento',
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0),
                            borderSide:
                                BorderSide(color: COLOR_PRIMARY, width: 2.0)),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ))))),
        Padding(
          padding: const EdgeInsets.only(right: 8.0, left: 8.0, top: 40.0),
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: double.infinity),
            child: ElevatedButton(
              onPressed: _sendToServer,
              style: ElevatedButton.styleFrom(
                primary: COLOR_PRIMARY,
                padding: EdgeInsets.only(top: 15, bottom: 15),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    side: BorderSide(color: COLOR_PRIMARY)),
              ),
              child: Text(
                'Salvar',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(right: 8.0, left: 8.0, top: 10.0),
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: double.infinity),
            child: ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              style: ElevatedButton.styleFrom(
                primary: Color(0xFF822A41),
                padding: EdgeInsets.only(top: 15, bottom: 15),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    side: BorderSide(color: Color(0xFF822A41))),
              ),
              child: Text(
                'Cancelar',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  TextEditingController birthController = TextEditingController();
  Future _selectDate() async {
    DateTime picked = await showDatePicker(
        context: context,
        locale: Locale("pt", "BR"),
        initialDate: DateTime.parse((loggedPerson.birth)),
        firstDate: new DateTime(1900),
        lastDate: new DateTime(2030));
    if (picked != null)
      setState(() => {
            birthSql = DateFormat('yyyy-MM-dd').format(picked),
            birthController.text = DateFormat('dd/MM/yyyy').format(picked)
          });
  }

  _sendToServer() async {
    if (_key.currentState.validate()) {
      setState(() {
        loading = true;
        sucess = false;
      });
      _key.currentState.save();

      await new Future.delayed(const Duration(seconds: 1));

      var m = null;

      PersonService service = new PersonService();

      try {
        //updateProgress('Validando...');

        loggedPerson = new ModelPerson(
            id: id,
            password: password,
            name: name,
            photo: photo,
            birth: birthSql,
            inserted_date: inserted_date,
            type: type,
            email: email);

        await service.postPerson(loggedPerson, _image);
        setState(() {
          loading = false;
          sucess = true;
        });
        await new Future.delayed(const Duration(milliseconds: 1600));
        setState(() {
          loading = false;
          sucess = false;
        });
        //showAlertDialog(context, 'JuBo', "Cadastro Efetuado!");

        //Navigator.pop(context);
      } catch (Exception) {
        setState(() => loading = false);
        //hideProgress();
        showAlertDialog(context, 'JuBo', "Problemas ao se cadastrar!");
      }
    } else {
      setState(() {
        _validate = AutovalidateMode.onUserInteraction;
      });
    }
  }

  @override
  void dispose() {
    _passwordController.dispose();
    _image = null;
    super.dispose();
  }
}
