import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.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;

class AddGroupDialog extends StatefulWidget {
  @override
  AddGroupDialog(this.isEdit, {this.grp});
  _AddGroupDialogState createState() => _AddGroupDialogState();
  final bool isEdit;
  final NAGroups? grp;
}

class _AddGroupDialogState extends State<AddGroupDialog>
    with TickerProviderStateMixin, ImagePickerListener {
  TextEditingController group_name = TextEditingController();
  bool showPassword = false;
  String initialCountry = 'NG';
  bool isProcessing = false;
  bool is_admin = false;
  late ImagePickerHandler imagePicker;
  late AnimationController _controller;
  late ImageProvider<Object> _image;
  late File _imageFile;
  bool hasfile = false;

  PhoneNumber number = PhoneNumber(isoCode: 'NG');

  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
    imagePicker = ImagePickerHandler(this, _controller);
    imagePicker.init();
    if (widget.isEdit) {
      _image = NetworkImage(
        dataUrl + widget.grp!.photo,
      );
      group_name = TextEditingController(text: widget.grp!.groupName);
    } else {
      _image = const AssetImage(
        appLogo,
      );
    }
  }

  @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
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Container(
        alignment: Alignment.center,
        child: Container(
          margin: const EdgeInsets.all(8.0),
          padding: const EdgeInsets.all(20.0),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.0),
            color: appColors.backgroundColor(context),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const SizedBox(height: 10.0),
              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: 10.0),
              Text(
                widget.isEdit ? "Edit Group Name" : "Enter Unique Name",
                style: TextStyle(
                    fontSize: 17.0,
                    color: appColors.armyColor(context),
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              const Divider(),
              const SizedBox(height: 30.0),
              SizedBox(
                width: double.infinity,
                child: buildTextField("GROUP NAME", "", false, group_name),
              ),
              const SizedBox(height: 40.0),
              SizedBox(
                width: double.infinity,
                child: getElevatedButton(
                    appColors.armyColor(context),
                    isProcessing
                        ? "Please wait..."
                        : widget.isEdit
                            ? "EDIT GROUP"
                            : "ADD GROUP", () {
                  addGroup().then((b) {
                    print("returning bb = $b");
                    if (b) {
                      Navigator.pop(context);
                    }
                  });
                }),
              ),
              const SizedBox(height: 40.0),
              getOutlinedButton(appColors.armyColor(context), "Close", () {
                Navigator.pop(context, null);
              }),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildTextField(String labelText, String placeholder,
      bool isPasswordTextField, TextEditingController controller) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 35.0),
      child: TextField(
        maxLength: 30,
        controller: controller,
        obscureText: isPasswordTextField ? showPassword : false,
        style: TextStyle(color: appColors.textColor(context)),
        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: TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.bold,
              color: appColors.textColor(context),
            ),
            floatingLabelBehavior: FloatingLabelBehavior.always,
            hintText: placeholder,
            hintStyle: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: appColors.textColorSecondary(context),
            )),
      ),
    );
  }

  Future<bool> addGroup() async {
    setState(() {
      isProcessing = true;
    });
    if (group_name.text.isEmpty) {
      showAlert(
          context, AlertDialogType.ERROR, "Error", "Please enter a group name");
      setState(() {
        isProcessing = false;
      });
      return false;
    }
    bool bResult = false;
    String url = widget.isEdit ? "editgroup" : "creategroup";
    var request = http.MultipartRequest("POST", Uri.parse(appApi + url));
    request.fields['group_name'] = group_name.text;
    if (widget.isEdit) {
      request.fields['id'] = widget.grp!.id.toString();
    }
    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") {
              /* group_name.clear();
              setState(() {
                _image = const AssetImage(
                  appLogo,
                );
                hasfile = false;
              }); */
              if (widget.isEdit) {
                widget.grp!.setGroupName(group_name.text);
                if (hasfile) {
                  widget.grp!.setPhoto("groups/" +
                      group_name.text.replaceAll(" ", "-").toLowerCase() +
                      pp.extension(_imageFile.path));
                }
                Navigator.of(context).pop(widget.grp!);
              } else {
                Navigator.of(context).pop(null);
              }
              bResult = true;
            } else {
              showAlert(context, AlertDialogType.ERROR, "Error",
                  data["data"]["message"]);
            }
          }
        } catch (e) {
          print("Error: " + e.toString());
          showAlert(context, AlertDialogType.ERROR, "Error", e.toString());
        }
      });
    });

    setState(() {
      isProcessing = false;
    });
    return bResult;
  }
}
