/**
 * Author: Aparna Dulal
 * profile: https://github.com/ambikadulal
  */
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:naim/classes/Auth.dart';
import 'package:naim/classes/appdata.dart';
import 'package:naim/classes/assets.dart';
import 'package:naim/widgets/image_picker_handler.dart';
import 'package:naim/widgets/input.dart';
import 'package:path/path.dart' as pp;
import 'package:http/http.dart' as http;

import 'auth/createpass.dart';
import 'home.dart';

class ProfileSettings extends StatefulWidget {
  @override
  ProfileSettings(this.isFirst);
  _ProfileSettingsState createState() => _ProfileSettingsState();

  bool isFirst;
}

class _ProfileSettingsState extends State<ProfileSettings>
    with TickerProviderStateMixin, ImagePickerListener {
  static final String path = "lib/src/pages/settings/profilesettings.dart";

  TextEditingController firstController =
      TextEditingController(text: appData.dbUser["firstname"]);

  TextEditingController lastController =
      TextEditingController(text: appData.dbUser["lastname"]);

  TextEditingController titleController =
      TextEditingController(text: appData.dbUser["title"]);

  TextEditingController usernameController =
      TextEditingController(text: appData.dbUser["username"]);

  bool showPassword = false;
  bool isSaving = false;
  bool hasfile = false;
  late ImagePickerHandler imagePicker;
  late AnimationController _controller;
  late ImageProvider<Object> _image;
  late File _imageFile;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
    imagePicker = ImagePickerHandler(this, _controller);
    imagePicker.init();
    _image = NetworkImage(
      dataUrl + appData.dbUser["photo"],
    );
  }

  @override
  userImage(File _image) {
    setState(() {
      _imageFile = _image;
      hasfile = true;
      this._image = FileImage(_imageFile);
      //_image_url = _image.path;
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void setState(fn) {
    if (mounted) {
      super.setState(fn);
    }
  }

  @override
  Widget build(BuildContext context) {
    appData.context = context;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back,
            color: armyGreen,
          ),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
      body: Container(
        padding: const EdgeInsets.only(left: 16, top: 15, right: 16),
        child: GestureDetector(
          onTap: () {
            FocusScope.of(context).unfocus();
          },
          child: ListView(
            children: [
              const Center(
                child: Text(
                  "Edit Profile",
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
                ),
              ),
              const SizedBox(
                height: 25,
              ),
              Center(
                child: Stack(
                  children: [
                    Container(
                      width: 130,
                      height: 130,
                      decoration: BoxDecoration(
                          border: Border.all(
                              width: 4,
                              color: Theme.of(context).scaffoldBackgroundColor),
                          boxShadow: [
                            BoxShadow(
                                spreadRadius: 2,
                                blurRadius: 10,
                                color: Colors.black.withOpacity(0.1),
                                offset: const Offset(0, 10))
                          ],
                          shape: BoxShape.circle,
                          image: DecorationImage(
                              fit: BoxFit.cover, image: _image)),
                    ),
                    Positioned(
                        bottom: 0,
                        right: 0,
                        child: InkWell(
                          onTap: () {
                            imagePicker.showDialog(context);
                          },
                          child: Container(
                            height: 40,
                            width: 40,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(
                                width: 4,
                                color:
                                    Theme.of(context).scaffoldBackgroundColor,
                              ),
                              color: armyGreen,
                            ),
                            child: const Icon(
                              Icons.edit,
                              color: Colors.white,
                            ),
                          ),
                        )),
                  ],
                ),
              ),
              const SizedBox(
                height: 35,
              ),
              buildTextField("Username", "", false, usernameController),
              buildTextField("First Name", "", false, firstController),
              buildTextField("Last Name", "", false, lastController),
              buildTextField("Title", "", false, titleController),
              const SizedBox(
                height: 35,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  getOutlinedButton(armyGreen, "CANCEL", () {
                    Navigator.of(context).pop();
                  }),
                  const SizedBox(
                    width: 20,
                  ),
                  getElevatedButton(
                      armyGreen, isSaving ? "Please Wait..." : "SAVE", () {
                    if (!isSaving) {
                      updateProfile(context);
                    }
                  }),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  updateProfile(BuildContext context) async {
    setState(() {
      isSaving = true;
    });
    bool bGo = true;
    String msg = "";
    if (usernameController.text.isEmpty) {
      bGo = false;
      msg = "Please select a username";
    } else if (firstController.text.isEmpty) {
      bGo = false;
      msg = "Please enter your first name";
    } else if (lastController.text.isEmpty) {
      bGo = false;
      msg = "Please enter your last name";
    } else if (titleController.text.isEmpty) {
      bGo = false;
      msg = "Please enter your title";
    }

    if (!bGo) {
      setState(() {
        isSaving = false;
      });
      showAlert(context, AlertDialogType.ERROR, "Sorry", msg);
      return;
    }

    var request =
        http.MultipartRequest("POST", Uri.parse(appApi + "updateprofile"));
    request.fields['firstname'] = firstController.text;
    request.fields["lastname"] = lastController.text;
    request.fields["username"] = usernameController.text;
    request.fields["title"] = titleController.text;
    if (hasfile) {
      request.fields["has_file"] = "1";
      request.files.add(
          await http.MultipartFile.fromPath('profile_pic', _imageFile.path));
    } else {
      request.fields["has_file"] = "0";
    }
    request.fields["token"] = appData.dbUser['token'];
    request.send().then((response) {
      http.Response.fromStream(response).then((onValue) {
        print(onValue.body);
        try {
          var data = json.decode(onValue.body);
          if (data["result"] != null) {
            if (data["result"] == "success") {
              print('it was success');
              showAlert(context, AlertDialogType.SUCCESS, "Success",
                  "Profile Updated");
              if (hasfile) {
                appData.dbUser["photo"] = "users/" +
                    appData.dbUser["id"].toString() +
                    "/user" +
                    pp.extension(_imageFile.path);
              }
              appData.dbUser["firstname"] = firstController.text;
              appData.dbUser["lastname"] = lastController.text;
              appData.dbUser["username"] = usernameController.text;
              appData.dbUser["title"] = titleController.text;

              if (widget.isFirst) {
                if (appData.dbUser['passkey'] == "") {
                  //CreatePassPage
                  Navigator.of(context).pushAndRemoveUntil(
                      MaterialPageRoute(
                          builder: (context) => CreatePassPage(true)),
                      (Route<dynamic> route) => false);
                } else {
                  Navigator.of(context).pushAndRemoveUntil(
                      MaterialPageRoute(builder: (context) => HomePage()),
                      (Route<dynamic> route) => false);
                }
              } else {
                Navigator.of(context).pop();
              }
            } else {
              showAlert(context, AlertDialogType.ERROR, "Error",
                  data["data"]["message"]);
            }
          }
        } catch (e) {
          print("Error: " + e.toString());
          showAlert(context, AlertDialogType.ERROR, "Error", e.toString());
        }
      });
    });

    setState(() {
      isSaving = false;
    });
  }

  Widget buildTextField(String labelText, String placeholder,
      bool isPasswordTextField, TextEditingController controller) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 35.0),
      child: TextField(
        controller: controller,
        obscureText: isPasswordTextField ? showPassword : false,
        decoration: InputDecoration(
            suffixIcon: isPasswordTextField
                ? IconButton(
                    onPressed: () {
                      setState(() {
                        showPassword = !showPassword;
                      });
                    },
                    icon: const Icon(
                      Icons.remove_red_eye,
                      color: Colors.grey,
                    ),
                  )
                : null,
            contentPadding: const EdgeInsets.only(bottom: 3),
            labelText: labelText,
            labelStyle: const TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
            floatingLabelBehavior: FloatingLabelBehavior.always,
            hintText: placeholder,
            hintStyle: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            )),
      ),
    );
  }
}
