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_image_compress/flutter_image_compress.dart';
import 'package:flutter/material.dart';
//import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter/services.dart';
import 'package:jubo/control/personService.dart';
import 'package:jubo/login.dart';
import 'package:jubo/main.dart';
import 'package:jubo/model/person.dart';
import 'package:jubo/preLogin.dart';
import 'package:jubo/ui/loading.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;

class SignUpScreen extends StatefulWidget {
  @override
  State createState() => _SignUpState();
}

class _SignUpState extends State<SignUpScreen> {
  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;
  ModelPerson person;
  bool loading = false;

  @override
  Widget build(BuildContext context) {
    try {
      if (Platform.isAndroid) {
        retrieveLostData();
      }
    } catch (e) {}

    return loading
        ? Loading()
        : Scaffold(
            appBar: AppBar(
              elevation: 0.0,
              backgroundColor: Colors.transparent,
              iconTheme: IconThemeData(color: Colors.black),
            ),
            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>[
        new Align(
            alignment: Alignment.topLeft,
            child: TextButton(
              child: Icon(
                Icons.arrow_back,
                size: 30.0,
                color: COLOR_PRIMARY,
              ),
              onPressed: () {
                Navigator.pushReplacement(context,
                    MaterialPageRoute(builder: (context) => PreLogin()));
              },
            )),
        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.asset(
                            'assets/images/placeholder.jpg',
                            fit: BoxFit.cover,
                          )
                        : Image.file(
                            _image,
                            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(
                    validator: validateName,
                    onSaved: (String val) {
                      name = val;
                    },
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        hintText: '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(
                    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),
                        ))))),
        ConstrainedBox(
            constraints: BoxConstraints(minWidth: double.infinity),
            child: Padding(
                padding:
                    const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
                child: Container(
                  padding: const EdgeInsets.only(right: 15.0, left: 15.0),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey),
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: DropdownButton<String>(
                      underline: Text(""),
                      value: type,
                      //icon: const Icon(Icons.arrow_downward),
                      iconSize: 0,
                      iconEnabledColor: Colors.transparent,
                      hint: Text("Tipo"),
                      //style: const TextStyle(color: Colors.deepPurple),
                      /*underline: Container(
                  height: 2,
                  color: Colors.deepPurpleAccent,
                ),*/
                      onChanged: (newValue) {
                        setState(() {
                          type = newValue;
                        });
                      },
                      items: [
                        DropdownMenuItem(
                          child: Text("Usuário"),
                          value: "Customer",
                        ),
                        DropdownMenuItem(
                          child: Text("Artista"),
                          value: "Artist",
                        ),
                        DropdownMenuItem(
                          child: Text("Local"),
                          value: "Spot",
                        ),
                      ]

                      /* items: <String>['Usuário', 'Artista']
                        .map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),*/
                      ),
                )

                /*TextFormField(
                keyboardType: TextInputType.text,
                textInputAction: TextInputAction.next,
                onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                validator: validateMobile,
                onSaved: (String val) {
                  type = val;
                },
                decoration: InputDecoration(
                  contentPadding:
                      new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                  fillColor: Colors.white,
                  hintText: 'Tipo',
                  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(
                obscureText: true,
                textInputAction: TextInputAction.next,
                onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                controller: _passwordController,
                validator: validatePassword,
                onSaved: (String val) {
                  password = val;
                },
                style: TextStyle(height: 0.8, fontSize: 18.0),
                cursorColor: COLOR_PRIMARY,
                decoration: InputDecoration(
                    contentPadding:
                        new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                    fillColor: Colors.white,
                    hintText: 'Senha',
                    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(
                textInputAction: TextInputAction.done,
                onFieldSubmitted: (_) {
                  //_sendToServer();
                },
                obscureText: true,
                validator: (val) =>
                    validateConfirmPassword(_passwordController.text, val),
                onSaved: (String val) {
                  confirmPassword = val;
                },
                style: TextStyle(height: 0.8, fontSize: 18.0),
                cursorColor: COLOR_PRIMARY,
                decoration: InputDecoration(
                    contentPadding:
                        new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                    fillColor: Colors.white,
                    hintText: 'Confirmar senha',
                    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(
                'Começar',
                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: new DateTime.now(),
        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);
      _key.currentState.save();

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

     // _image = await compressFile(_image);

      var m = null;

      PersonService service = new PersonService();

      try {
        //updateProgress('Validando...');
        person = new ModelPerson(
            password: password,
            name: name,
            photo: "",
            birth: birthSql,
            type: type,
            email: email);

        await service.postPerson(person, _image);

        showAlertDialog(context, 'JuBo', "Cadastro Efetuado!");
        Navigator.pushReplacement(
            context,
            MaterialPageRoute(
                builder: (context) => MyStatefulWidget(selectedIndex: 0)));
      } 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();
  }
}
