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

import 'package:dio/dio.dart';
import 'package:encrypt/encrypt.dart';
import 'package:flutter/cupertino.dart';
/**
 * Author: Aparna Dulal
 * profile: https://github.com/ambikadulal
  */
import 'package:flutter/material.dart';
import 'package:naim/classes/Authenticate.dart';
import 'package:naim/classes/appdata.dart';
import 'package:naim/classes/assets.dart';
import 'package:naim/screens/addgroup.dart';
import 'package:naim/screens/adduser.dart';
import 'package:naim/screens/broadcast.dart';
import 'package:naim/screens/managegroup.dart';
import 'package:naim/screens/manageusers.dart';
import 'package:naim/screens/onboarding.dart';
import 'package:naim/screens/profile_settings.dart';
import 'package:naim/screens/viewbroadcast.dart';
import 'package:naim/widgets/input.dart';

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

class SettingsPage extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  bool isSigningout = false;

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

  updateUsername() async {
    print("at updating username =====");
    String username = appData.dbUser['username'];
    if (appData.passKey != "") {
      Encrypted passkey = encryptIt(username, appData.passKey);

      appData.dbUser["passkey"] = passkey.base64;

      try {
        var dio = Dio();
        dio.options.baseUrl = appApi;
        var formData = {
          "passkey": passkey.base64,
          "token": appData.dbUser['token']
        };
        var response = await dio.post(
          "updatepasskey",
          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") {
          } else {
            print(data["data"]["message"]);
          }
        }
      } catch (e) {
        print(e.toString());
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: appColors.backgroundColor(context),
        elevation: 0,
        leading: IconButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          icon: Icon(
            Icons.arrow_back,
            color: appColors.armyColor(context),
          ),
        ),
      ),
      backgroundColor: appColors.backgroundColor(context),
      body: Container(
        padding: EdgeInsets.only(left: 16, top: 25, right: 16),
        child: ListView(
          children: [
            Center(
              child: Text(
                "Settings",
                style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.w500,
                    color: appColors.armyColor(context)),
              ),
            ),
            const SizedBox(
              height: 40,
            ),
            Row(
              children: [
                Icon(
                  Icons.person,
                  color: appColors.armyColor(context),
                ),
                const SizedBox(
                  width: 8,
                ),
                Text(
                  "Account",
                  style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: appColors.textColor(context)),
                ),
              ],
            ),
            const Divider(
              height: 15,
              thickness: 2,
            ),
            const SizedBox(
              height: 10,
            ),
            buildAccountOptionRow(context, "Edit Profile", () async {
              await Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => ProfileSettings(false)));
              updateUsername();
            }),
            buildAccountOptionRow(context, "Add User", () async {
              await showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AddUserDialog();
                },
              );
            }),
            buildAccountOptionRow(context, "Manange Users", () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => ManageUsersPage()));
            }),
            buildAccountOptionRow(context, "Create Group", () async {
              await showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AddGroupDialog(false);
                },
              );
            }),
            buildAccountOptionRow(context, "Manage Groups", () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => ManageGroupsPage()));
            }),
            buildAccountOptionRow(context, "Send Broadcast", () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => BroadCastPage()));
            }),
            buildAccountOptionRow(context, "View Broadcasts", () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => ViewBroadcastPage()));
            }),
            const SizedBox(
              height: 40,
            ),
            /* Row(
              children: [
                Icon(
                  Icons.volume_up_outlined,
                  color: Colors.green,
                ),
                SizedBox(
                  width: 8,
                ),
                Text(
                  "Notifications",
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
              ],
            ),
            Divider(
              height: 15,
              thickness: 2,
            ),
            SizedBox(
              height: 10,
            ),
            buildNotificationOptionRow("New update", true),
            buildNotificationOptionRow("Account Status", false),
            SizedBox(
              height: 50,
            ), */
            Center(
              child: getElevatedButton(appColors.armyColor(context),
                  isSigningout ? "Please wait..." : "Log Out", () async {
                setState(() {
                  isSigningout = true;
                });
                GUser n = GUser();
                await n.signOut();
                Navigator.of(context).pushAndRemoveUntil(
                    MaterialPageRoute(builder: (context) => Onboarding()),
                    (Route<dynamic> route) => false);
              }),
            )
          ],
        ),
      ),
    );
  }

  Row buildNotificationOptionRow(String title, bool isActive) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          title,
          style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w500,
              color: Colors.grey[600]),
        ),
        Transform.scale(
            scale: 0.7,
            child: CupertinoSwitch(
              value: isActive,
              onChanged: (bool val) {},
            ))
      ],
    );
  }

  Widget buildAccountOptionRow(
      BuildContext context, String title, VoidCallback func) {
    if (title.toLowerCase() == "edit profile" ||
        title.toLowerCase() == "view broadcasts" ||
        appData.dbUser["is_admin"] == 1) {
      return InkWell(
        onTap: func,
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 12.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                title,
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                  color: appColors.textColor(context),
                ),
              ),
              Icon(
                Icons.arrow_forward_ios,
                color: appColors.armyColor(context),
              ),
            ],
          ),
        ),
      );
    } else {
      return GestureDetector(onTap: () {}, child: Container());
    }
  }
}
