/**
 * 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/settings.dart';
import 'package:naim/screens/userdetails.dart';

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

class ManageUsersPage extends StatefulWidget {
  @override
  ManageUsersPage({this.bSelect = false});
  _ManageUsersPageState createState() => _ManageUsersPageState();
  bool bSelect = false;
}

class _ManageUsersPageState extends State<ManageUsersPage> {
  List<NAUsers> _searchList = [];
  bool isSearching = false;
  List<NAUsers> friends = [];
  bool isProcessing = false;

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

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

  @override
  Widget build(BuildContext context) {
    appData.context = 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: InkWell(
            onTap: () async {
              if (widget.bSelect) {
                Navigator.of(context).pop(friend);
              } else {
                await Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => UserDetails(friend)));
                loadUsers();
              }
            },
            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.username.isEmpty
                                  ? "No Name"
                                  : "${friend.lastname} ${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.armyColor(context),
                          icon: const Icon(FontAwesomeIcons.infoCircle),
                          onPressed: () async {
                            if (widget.bSelect) {
                              Navigator.of(context).pop(friend);
                            } else {
                              await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          UserDetails(friend)));
                              loadUsers();
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );

    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: appColors.armyColor(context),
        child: const Icon(Icons.plus_one),
        onPressed: () async {
          await showDialog(
            context: context,
            builder: (BuildContext context) {
              return AddUserDialog();
            },
          );
          loadUsers();
        },
      ),
      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,
                          ),
                          Text(
                            widget.bSelect ? "Select User" : 'Manage Users',
                            style: const 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 Users...',
                    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.firstname.contains(search) ||
          p.lastname.contains(search) ||
          p.username.contains(search) ||
          p.title.contains(search)) {
        setState(() {
          _searchList.add(p);
        });
      }
    });
  }

  loadUsers() async {
    setState(() {
      isProcessing = true;
    });
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;
      var formData = {"token": appData.dbUser['token']};
      var response = await dio.post(
        widget.bSelect ? "getallusersplusme" : "getallusers",
        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;
    });
  }
}
