import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:naim/classes/Auth.dart';
import 'package:naim/classes/assets.dart';
import 'package:naim/widgets/input.dart';

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

class UserDetails extends StatefulWidget {
  @override
  UserDetailsState createState() => UserDetailsState();
  final NAUsers nuser;
  UserDetails(this.nuser);
}

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          backgroundColor: appColors.armyColor(context),
          child: Icon(Platform.isIOS ? Icons.arrow_back_ios : Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        backgroundColor: appColors.backgroundColor(context),
        body: SafeArea(
          child: ListView(
            children: <Widget>[
              Stack(
                children: <Widget>[
                  Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        fit: BoxFit.cover,
                        colorFilter: ColorFilter.mode(
                            appColors.backgroundColor(context),
                            BlendMode.multiply),
                        image: AssetImage(appColors.bkImg(context)),
                      ),
                    ),
                    width: double.infinity,
                    height: 330,
                  ),
                  Positioned(
                    top: 10,
                    right: 30,
                    child: InkWell(
                      onTap: () {
                        Navigator.of(context).pop();
                      },
                      child: Icon(
                        Icons.close,
                        color: appColors.textColor(context),
                      ),
                    ),
                  ),
                  Column(
                    children: <Widget>[
                      Container(
                          height: 90,
                          margin: EdgeInsets.only(top: 60),
                          child: CircleAvatar(
                            radius: 50,
                            backgroundColor: Colors.white,
                            backgroundImage:
                                NetworkImage(dataUrl + widget.nuser.photo),
                          )),
                      const Padding(
                        padding: EdgeInsets.all(4),
                      ),
                      Text(
                        widget.nuser.username.isNotEmpty
                            ? "${widget.nuser.firstname} ${widget.nuser.lastname}"
                            : widget.nuser.phone,
                        style: TextStyle(
                            color: appColors.armyColor(context),
                            fontWeight: FontWeight.w500,
                            fontSize: 20),
                        textAlign: TextAlign.center,
                      ),
                      const Padding(
                        padding: EdgeInsets.all(4),
                      ),
                      Text(
                        widget.nuser.username.isNotEmpty
                            ? widget.nuser.username
                            : "",
                        style: const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w400,
                            fontSize: 16),
                        textAlign: TextAlign.center,
                      ),
                      userInfo(context)
                    ],
                  )
                ],
              ),
            ],
          ),
        ));
  }

  Widget userInfo(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10),
      child: Column(
        children: <Widget>[
          Card(
            margin: const EdgeInsets.only(top: 30),
            child: Container(
              color: appColors.backgroundColor2(context),
              alignment: Alignment.topLeft,
              padding: const EdgeInsets.all(15),
              child: Column(
                children: <Widget>[
                  Container(
                    alignment: Alignment.topLeft,
                    child: Text(
                      "Actions",
                      style: TextStyle(
                        color: appColors.armyColor(context),
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                      textAlign: TextAlign.left,
                    ),
                  ),
                  const Divider(
                    color: Colors.black38,
                  ),
                  Container(
                      child: Column(
                    children: <Widget>[
                      ListTile(
                        onTap: () {
                          toggleStatus();
                        },
                        contentPadding: const EdgeInsets.symmetric(
                            horizontal: 12, vertical: 4),
                        leading: Icon(
                          Icons.start,
                          color: appColors.armyColor(context),
                        ),
                        title: Text(
                            widget.nuser.status
                                ? "Disable Account"
                                : "Enable Account",
                            style:
                                TextStyle(color: appColors.textColor(context))),
                        subtitle: Text("Enable / Disable user account",
                            style: TextStyle(
                                color: appColors.textColorSecondary(context),
                                fontSize: 12)),
                      ),
                      ListTile(
                        onTap: () {
                          toggleAdmin();
                        },
                        leading: Icon(
                          Icons.admin_panel_settings,
                          color: appColors.armyColor(context),
                        ),
                        title: Text(
                            widget.nuser.isAdmin
                                ? "Make a User"
                                : "Make An Admin",
                            style:
                                TextStyle(color: appColors.textColor(context))),
                        subtitle: Text(
                            "Change user account to admin or normal user",
                            style: TextStyle(
                                color: appColors.textColorSecondary(context),
                                fontSize: 12)),
                      ),
                      const ListTile(
                        title: Text(""),
                      ),
                      ListTile(
                        onTap: () async {
                          bool rr = await showOptionAlert(
                              context,
                              AlertDialogType.INFO,
                              "Delete User?",
                              "Are you sure you want to delete this user?",
                              "Yes, Delete") as bool;
                          if (rr) {
                            deleteUser();
                          }
                        },
                        leading: Icon(
                          Icons.delete,
                          color: appColors.amberColor(context),
                        ),
                        title: Text("Delete Account",
                            style: TextStyle(
                                color: appColors.amberColor(context))),
                        subtitle: Text("Permanently remove user account",
                            style: TextStyle(
                                color: appColors.textColorSecondary(context),
                                fontSize: 12)),
                      ),
                    ],
                  ))
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  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() async {
    bool bResult = false;
    //print(appData.dbUser)
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;

      var formData = {"token": appData.dbUser['token'], "id": widget.nuser.id};
      var response = await dio.post(
        "deleteuser",
        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") {
          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;
  }

  toggleStatus() async {
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;
      var formData = {
        "token": appData.dbUser['token'],
        "id": widget.nuser.id,
        "status": !widget.nuser.status ? 1 : 0
      };
      var response = await dio.post(
        "togglestatus",
        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.setStatus(!widget.nuser.status);
          });
          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());
    }
  }
}
