/**
 * Author: Siddhartha Joshi
 * profile: https://github.com/cimplesid
  */

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

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:naim/classes/assets.dart';
import 'package:naim/screens/addgroup.dart';
import 'package:naim/screens/groupdetails.dart';
import 'package:naim/screens/settings.dart';
import 'package:naim/screens/userdetails.dart';

import '../classes/Auth.dart';
import '../classes/appdata.dart';

class ManageGroupsPage extends StatefulWidget {
  @override
  ManageGroupsPage();
  _ManageGroupsPageState createState() => _ManageGroupsPageState();
}

class _ManageGroupsPageState extends State<ManageGroupsPage> {
  List<NAGroups> _searchList = [];
  bool isSearching = false;
  List<NAGroups> friends = [];
  bool isProcessing = false;

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

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

  String getUsercount(int c) {
    var str = "user";
    if (c > 1) {
      str = "users";
    }
    return "$c $str";
  }

  @override
  Widget build(BuildContext context) {
    appData.context = context;
    createTile(NAGroups 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: InkWell(
            onTap: () async {
              await Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => GroupDetails(friend)));
              loadGroups();
            },
            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: 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>[
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: <Widget>[
                            Text(
                              friend.groupName,
                              style: TextStyle(
                                color: appColors.armyColor(context),
                                fontSize: 18.0,
                              ),
                            )
                          ],
                        ),
                        const SizedBox(height: 10.0),
                        Text(
                          getUsercount(friend.userCount),
                          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.armyColor(context),
                          icon: const Icon(FontAwesomeIcons.infoCircle),
                          onPressed: () async {
                            await Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>
                                        GroupDetails(friend)));
                            loadGroups();
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );

    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: appColors.armyColor(context),
        child: const Icon(Icons.plus_one),
        onPressed: () async {
          await showDialog(
            context: context,
            builder: (BuildContext context) {
              return AddGroupDialog(false);
            },
          );
          loadGroups();
        },
      ),
      backgroundColor: appColors.backgroundColor(context),
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.cover,
            colorFilter: ColorFilter.mode(
                appColors.backgroundColor(context), BlendMode.multiply),
            image: AssetImage(camobkimg),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.fromLTRB(20.0, 40.0, 20.0, 20.0),
              child: Row(
                children: [
                  Expanded(
                      flex: 5,
                      child: Row(
                        children: [
                          Container(
                              width: 40,
                              height: 40,
                              decoration: const BoxDecoration(
                                image: DecorationImage(
                                  fit: BoxFit.contain,
                                  image: AssetImage(appLogo),
                                ),
                              )),
                          const SizedBox(
                            width: 10,
                          ),
                          const Text(
                            'Manage Groups',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 26.0,
                                fontWeight: FontWeight.bold,
                                shadows: <Shadow>[
                                  Shadow(
                                    offset: Offset(1.0, 1.0),
                                    blurRadius: 1.0,
                                    color: Color.fromARGB(255, 0, 0, 0),
                                  )
                                ]),
                          ),
                        ],
                      )),
                  Expanded(
                    child: InkWell(
                      onTap: () async {
                        Navigator.of(context).pop();
                      },
                      child: Icon(Icons.close,
                          color: appColors.textColor(context)),
                    ),
                  )
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
              child: TextField(
                onChanged: (val) {
                  if (val.isNotEmpty) {
                    searchList(val);
                  }
                  setState(() {
                    isSearching = val.isNotEmpty;
                  });
                },
                decoration: InputDecoration(
                    hintText: 'Search Groups...',
                    hintStyle: TextStyle(
                      color: appColors.textColor(context),
                    ),
                    filled: true,
                    fillColor: appColors.backgroundColor(context),
                    suffixIcon: Icon(
                      Icons.search,
                      color: appColors.armyColor(context),
                    ),
                    border: InputBorder.none),
              ),
            ),
            Flexible(
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                physics: const BouncingScrollPhysics(),
                child: Padding(
                  padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                  child: isProcessing
                      ? Center(
                          child: Text('Please wait...',
                              style: TextStyle(
                                  color: appColors.textColor(context),
                                  fontWeight: FontWeight.bold)))
                      : Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: isSearching
                              ? _searchList
                                  .map((book) => createTile(book))
                                  .toList()
                              : friends
                                  .map((book) => createTile(book))
                                  .toList(),
                        ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  searchList(String search) {
    setState(() {
      _searchList = [];
    });
    friends.forEach((p) {
      if (p.groupName.contains(search)) {
        setState(() {
          _searchList.add(p);
        });
      }
    });
  }

  loadGroups() async {
    setState(() {
      isProcessing = true;
    });
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;
      var formData = {"token": appData.dbUser['token']};
      var response = await dio.post(
        "getallgroups",
        data: formData,
        options: Options(
          method: 'POST',
          responseType: ResponseType.plain,
          headers: {
            HttpHeaders.contentLengthHeader:
                formData.length, // set content-length
          },
        ),
      );
      print(response.data);
      var data = json.decode(response.data);
      if (data["result"] != null) {
        if (data["result"] == "success") {
          setState(() {
            friends.clear();
          });
          data["data"].forEach((dat) {
            var g = NAGroups.fromJson(dat);

            var map = {
              'photo': dat["user_photo"],
              'isAdmin': dat["is_admin"],
              'title': dat['title'],
              'firstname': dat['firstname'],
              'lastname': dat['lastname'],
              'username': dat['username'],
              'phone': dat['phone'],
              'id': dat['user_id'],
              'status': dat['status']
            };
            NAUsers u = NAUsers.fromJson(map);
            g.setCreatedBy(u);
            setState(() {
              friends.add(g);
            });
          });
        }
      }
    } catch (e) {
      print("Error: " + e.toString());
    }
    setState(() {
      isProcessing = false;
    });
  }
}
