import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:naim/classes/Auth.dart';
import 'package:naim/classes/assets.dart';
import 'package:naim/screens/addgroup.dart';
import 'package:naim/screens/manageusers.dart';
import 'package:naim/screens/userdetails.dart';
import 'package:naim/widgets/input.dart';

import '../classes/appdata.dart';
import '../classes/cipher.dart';
import '../classes/message.dart';

class GroupDetails extends StatefulWidget {
  @override
  GroupDetailsState createState() => GroupDetailsState();
  final NAGroups ngroup;
  GroupDetails(this.ngroup);
}

class GroupDetailsState extends State<GroupDetails> {
  static final String path = "lib/src/pages/profile/profile7.dart";

  List<NAUsers> _searchList = [];
  bool isSearching = false;
  List<NAUsers> friends = [];
  bool isProcessing = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadUsers();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          backgroundColor: appColors.armyColor(context),
          child: const Icon(Icons.plus_one),
          onPressed: () async {
            var user = await Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => ManageUsersPage(bSelect: true)))
                as NAUsers;
            addUsertoGroup(user);
          },
        ),
        backgroundColor: appColors.backgroundColor(context),
        body: SafeArea(
          child: ListView(
            children: <Widget>[
              Stack(
                children: <Widget>[
                  Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        fit: BoxFit.cover,
                        colorFilter: const ColorFilter.mode(
                            Colors.black54, BlendMode.multiply),
                        image: NetworkImage(dataUrl + widget.ngroup.photo),
                      ),
                    ),
                    width: double.infinity,
                    height: 230,
                  ),
                  Positioned(
                    top: 10,
                    right: 30,
                    child: InkWell(
                      onTap: () {
                        Navigator.of(context).pop();
                      },
                      child: const Icon(
                        Icons.close,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Column(
                    children: <Widget>[
                      const Padding(
                        padding: EdgeInsets.all(4),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 20.0),
                        child: Text(
                          widget.ngroup.groupName,
                          style: const TextStyle(
                              color: Colors.blueGrey,
                              fontWeight: FontWeight.w900,
                              fontSize: 30),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      const Padding(
                        padding: EdgeInsets.all(4),
                      ),
                      Text(
                        "Created By - ${widget.ngroup.createdBy?.lastname}, ${widget.ngroup.createdBy?.firstname}",
                        style: const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w600,
                            fontSize: 17),
                        textAlign: TextAlign.center,
                      ),
                      Container(
                        margin:
                            const EdgeInsets.only(top: 77, left: 30, right: 30),
                        padding: const EdgeInsets.all(10),
                        child: Card(
                          color: appColors.backgroundColor2(context),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: <Widget>[
                              InkWell(
                                onTap: () async {
                                  bool rr = await showOptionAlert(
                                      context,
                                      AlertDialogType.INFO,
                                      "Delete Group?",
                                      "Are you sure you want to delete this group?",
                                      "Yes, Delete") as bool;
                                  if (rr) {
                                    deleteGroup();
                                  }
                                },
                                child: Column(
                                  children: <Widget>[
                                    Container(
                                        padding: const EdgeInsets.only(
                                            top: 15, bottom: 5),
                                        child: Icon(
                                          Icons.delete,
                                          color: appColors.amberColor(context),
                                        )),
                                    Container(
                                        padding:
                                            const EdgeInsets.only(bottom: 15),
                                        child: Text("Delete Group",
                                            style: TextStyle(
                                                color: appColors
                                                    .amberColor(context),
                                                fontSize: 16))),
                                  ],
                                ),
                              ),
                              InkWell(
                                onTap: () async {
                                  var val = await showDialog(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return AddGroupDialog(true,
                                          grp: widget.ngroup);
                                    },
                                  );
                                  if (val != null) {
                                    var grp = val as NAGroups;
                                    setState(() {
                                      widget.ngroup.setGroupName(grp.groupName);
                                      widget.ngroup.setPhoto(grp.photo);
                                    });
                                  }
                                },
                                child: Column(
                                  children: <Widget>[
                                    Container(
                                        padding: const EdgeInsets.only(
                                            top: 15, bottom: 5),
                                        child: Icon(
                                          Icons.edit,
                                          color: appColors.textColor(context),
                                        )),
                                    Container(
                                        padding:
                                            const EdgeInsets.only(bottom: 15),
                                        child: Text("Edit Group",
                                            style: TextStyle(
                                                color: appColors
                                                    .textColor(context),
                                                fontSize: 16))),
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                      userInfo(context)
                    ],
                  )
                ],
              ),
            ],
          ),
        ));
  }

  Widget userInfo(BuildContext context) {
    createTile(NAUsers friend) => Container(
          margin: const EdgeInsets.only(top: 20),
          decoration: BoxDecoration(
            color: appColors.backgroundColor(context),
            border: Border(
              bottom:
                  BorderSide(color: appColors.armyColor(context), width: 2.0),
            ),
          ),
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 10.0),
            child: Row(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.fromLTRB(8.0, 6.0, 16.0, 6.0),
                  child: InkWell(
                    onTap: () async {
                      await Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => UserDetails(friend)));
                      loadUsers();
                    },
                    child: Container(
                      width: 50.0,
                      height: 50.0,
                      decoration: BoxDecoration(
                        color: Colors.transparent,
                        image: DecorationImage(
                            image: NetworkImage(dataUrl + friend.photo),
                            fit: BoxFit.cover),
                        borderRadius: BorderRadius.circular(50.0),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      InkWell(
                        onTap: () async {
                          await Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => UserDetails(friend)));
                          loadUsers();
                        },
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: <Widget>[
                            Text(
                              friend.username.isEmpty
                                  ? "No Name"
                                  : "${friend.title} ${friend.firstname} ",
                              style: TextStyle(
                                color: appColors.armyColor(context),
                                fontSize: 18.0,
                              ),
                            ),
                            const SizedBox(width: 6.0),
                          ],
                        ),
                      ),
                      Text(
                        " - ${friend.title}",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: appColors.textColor(context),
                        ),
                      ),
                      const SizedBox(height: 10.0),
                      Text(
                        friend.phone,
                        style: TextStyle(
                          color: appColors.textColorSecondary(context),
                          fontSize: 16.0,
                        ),
                      ),
                    ],
                  ),
                ),
                Row(
                  children: <Widget>[
                    Container(
                      width: 42.0,
                      height: 42.0,
                      decoration: BoxDecoration(
                        color: appColors.backgroundColor(context),
                        borderRadius: BorderRadius.circular(50.0),
                      ),
                      child: IconButton(
                        color: appColors.amberColor(context),
                        icon: const Icon(Icons.delete),
                        onPressed: () async {
                          bool rr = await showOptionAlert(
                              context,
                              AlertDialogType.INFO,
                              "Remove User?",
                              "Are you sure you want to remove this user from group?",
                              "Yes, Delete") as bool;
                          if (rr) {
                            deleteUser(friend);
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
    return Container(
      padding: const EdgeInsets.all(10),
      child: Column(
        children: <Widget>[
          Card(
            child: Container(
              color: appColors.backgroundColor2(context),
              alignment: Alignment.topLeft,
              padding: const EdgeInsets.all(15),
              child: Column(
                children: <Widget>[
                  Container(
                    alignment: Alignment.topLeft,
                    child: Text(
                      "Group Members",
                      style: TextStyle(
                        color: appColors.armyColor(context),
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                      textAlign: TextAlign.left,
                    ),
                  ),
                  const Divider(
                    color: Colors.black38,
                  ),
                  Container(
                      child: isProcessing
                          ? const Center(child: Text('Please wait...'))
                          : Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: isSearching
                                  ? _searchList
                                      .map((book) => createTile(book))
                                      .toList()
                                  : friends
                                      .map((book) => createTile(book))
                                      .toList(),
                            ))
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  /* toggleAdmin() async {
    //print(appData.dbUser)
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;

      var formData = {
        "token": appData.dbUser['token'],
        "id": widget.nuser.id,
        "make_admin": !widget.nuser.isAdmin ? 1 : 0
      };
      var response = await dio.post(
        "toggleadmin",
        data: formData,
        options: Options(
          method: 'POST',
          responseType: ResponseType.plain,
          headers: {
            HttpHeaders.contentLengthHeader:
                formData.length, // set content-length
          },
        ),
      );
      print(response.data);
      print("respnse data ======= ==");
      var data = json.decode(response.data);
      if (data["result"] != null) {
        if (data["result"] == "success") {
          setState(() {
            widget.nuser.setAdmin(!widget.nuser.isAdmin);
          });
          showAlert(context, AlertDialogType.SUCCESS, "Success", "All Done");
        } else {
          showAlert(
              context, AlertDialogType.ERROR, "Error", data["data"]["message"]);
        }
      }
    } catch (e) {
      print("Error: " + e.toString());
      showAlert(context, AlertDialogType.ERROR, "Error", e.toString());
    }
  }
 */
  Future<bool> deleteUser(NAUsers user) async {
    bool bResult = false;
    //print(appData.dbUser)
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;

      var formData = {
        "token": appData.dbUser['token'],
        "group_id": widget.ngroup.id,
        "user_id": user.id
      };
      var response = await dio.post(
        "removeuserfromgroup",
        data: formData,
        options: Options(
          method: 'POST',
          responseType: ResponseType.plain,
          headers: {
            HttpHeaders.contentLengthHeader:
                formData.length, // set content-length
          },
        ),
      );
      print(response.data);
      print("respnse data ======= ==");
      var data = json.decode(response.data);
      if (data["result"] != null) {
        if (data["result"] == "success") {
          loadUsers();
          bResult = true;
        } else {
          showAlert(
              context, AlertDialogType.ERROR, "Error", data["data"]["message"]);
        }
      }
    } catch (e) {
      print("Error: " + e.toString());
      showAlert(context, AlertDialogType.ERROR, "Error", e.toString());
    }
    return bResult;
  }

  Future<bool> deleteGroup() async {
    bool bResult = false;
    //print(appData.dbUser)
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;

      var formData = {"token": appData.dbUser['token'], "id": widget.ngroup.id};
      var response = await dio.post(
        "deletegroup",
        data: formData,
        options: Options(
          method: 'POST',
          responseType: ResponseType.plain,
          headers: {
            HttpHeaders.contentLengthHeader:
                formData.length, // set content-length
          },
        ),
      );
      print(response.data);
      print("respnse data ======= ==");
      var data = json.decode(response.data);
      if (data["result"] != null) {
        if (data["result"] == "success") {
          bResult = true;
          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());
    }
    return bResult;
  }

  Future<void> addUsertoGroup(NAUsers user) async {
    //print(appData.dbUser)
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;

      var msg = Message(
          print: true,
          rnd: randomString(9),
          userid: appData.dbUser['id'],
          description: encryptIt(
                  '${user.phone} has been added to the group', appData.strPwd)
              .base64,
          type: "status",
          user: NAUsers.fromJson(appData.dbUser),
          timestamp: DateTime.now());

      var x = msg.getJSON(true, widget.ngroup.id);

      var formData = {
        "token": appData.dbUser['token'],
        "group_id": widget.ngroup.id,
        "user_id": user.id,
        "data": x
      };
      var response = await dio.post(
        "addusertogroup",
        data: formData,
        options: Options(
          method: 'POST',
          responseType: ResponseType.plain,
          headers: {
            HttpHeaders.contentLengthHeader:
                formData.length, // set content-length
          },
        ),
      );
      print(response.data);
      print("respnse data ======= ==");
      var data = json.decode(response.data);
      if (data["result"] != null) {
        if (data["result"] == "success") {
          if (appData.constat != "closed") {
            appData.channel!.sink.add(json.encode(
                {"type": "updategroupmembers", "group_id": widget.ngroup.id}));
          }
          loadUsers();
        } else {
          showAlert(
              context, AlertDialogType.ERROR, "Error", data["data"]["message"]);
        }
      }
    } catch (e) {
      print("Error: " + e.toString());
      showAlert(context, AlertDialogType.ERROR, "Error", e.toString());
    }
  }

  loadUsers() async {
    setState(() {
      isProcessing = true;
    });
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;
      var formData = {
        "token": appData.dbUser['token'],
        "group_id": widget.ngroup.id
      };
      var response = await dio.post(
        "getallusersbygroup",
        data: formData,
        options: Options(
          method: 'POST',
          responseType: ResponseType.plain,
          headers: {
            HttpHeaders.contentLengthHeader:
                formData.length, // set content-length
          },
        ),
      );
      print(response.data);
      print("respnse data ======= ==");
      var data = json.decode(response.data);
      if (data["result"] != null) {
        if (data["result"] == "success") {
          setState(() {
            friends.clear();
          });
          data["data"].forEach((dat) {
            setState(() {
              friends.add(NAUsers.fromJson(dat));
            });
          });
        }
      }
    } catch (e) {
      print("Error: " + e.toString());
    }
    setState(() {
      isProcessing = false;
    });
  }
}
