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

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
import 'package:naim/classes/Auth.dart';
import 'package:naim/classes/appdata.dart';
import 'package:naim/classes/assets.dart';
import 'package:naim/widgets/input.dart';

class AddUserDialog extends StatefulWidget {
  @override
  AddUserDialog();
  _AddUserDialogState createState() => _AddUserDialogState();
}

class _AddUserDialogState extends State<AddUserDialog> {
  TextEditingController cc = TextEditingController();
  String txtPhone = "";
  String initialCountry = 'NG';
  bool isProcessing = false;
  bool is_admin = false;
  PhoneNumber number = PhoneNumber(isoCode: 'NG');
  @override
  Widget build(BuildContext context) {
    //appData.context = context;
    return Material(
      type: MaterialType.transparency,
      child: Container(
        alignment: Alignment.center,
        child: Container(
          margin: const EdgeInsets.all(8.0),
          padding: const EdgeInsets.all(20.0),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.0),
            color: appColors.backgroundColor(context),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const SizedBox(height: 10.0),
              Container(
                width: 60,
                height: 60,
                decoration: const BoxDecoration(
                  image: DecorationImage(
                      fit: BoxFit.contain, image: AssetImage(appLogo)),
                ),
              ),
              const SizedBox(height: 10.0),
              Text(
                "New User's Phone Number",
                style: TextStyle(
                    fontSize: 17.0,
                    color: appColors.armyColor(context),
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              const Divider(),
              const SizedBox(height: 30.0),
              SizedBox(
                width: double.infinity,
                child: InternationalPhoneNumberInput(
                  textFieldController: cc,
                  onInputChanged: (PhoneNumber number) {
                    setState(() {
                      txtPhone = number.phoneNumber!;
                    });
                  },
                  onInputValidated: (bool value) {},
                  selectorConfig: const SelectorConfig(
                    selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
                  ),
                  ignoreBlank: true,
                  autoValidateMode: AutovalidateMode.disabled,
                  selectorTextStyle:
                      TextStyle(color: appColors.armyColor(context)),
                  initialValue: number,
                  cursorColor: appColors.textColor(context),
                  inputDecoration: InputDecoration(
                      hintText: "Phone Number",
                      hintStyle: TextStyle(
                          color: appColors.textColorSecondary(context))),
                  textStyle: TextStyle(color: appColors.textColor(context)),
                  formatInput: false,
                  searchBoxDecoration: InputDecoration(
                      filled: true,
                      hintText: "Search...",
                      hintStyle: TextStyle(
                          color: appColors.textColorSecondary(context)),
                      fillColor: appColors.backgroundColor(context)),
                  keyboardType: const TextInputType.numberWithOptions(
                      signed: true, decimal: true),
                  inputBorder: OutlineInputBorder(
                      borderSide:
                          BorderSide(color: appColors.armyColor(context))),
                  onSaved: (PhoneNumber number) {
                    print('On Saved: $number');
                  },
                ),
              ),
              const SizedBox(height: 40.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "Admin User",
                    style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w500,
                        color: appColors.textColor(context)),
                  ),
                  Transform.scale(
                      scale: 0.7,
                      child: CupertinoSwitch(
                        activeColor: appColors.armyColor(context),
                        value: is_admin,
                        onChanged: (bool val) {
                          setState(() {
                            is_admin = val;
                          });
                        },
                      ))
                ],
              ),
              const SizedBox(height: 40.0),
              SizedBox(
                width: double.infinity,
                child: getElevatedButton(appColors.armyColor(context),
                    isProcessing ? "Please wait..." : "ADD USER", () {
                  addUser().then((b) {
                    print("returning bb = $b");
                    if (b) {
                      showAlert(context, AlertDialogType.SUCCESS, "Success",
                          "User Created");
                      Navigator.pop(context);
                    }
                  });
                }),
              ),
              const SizedBox(height: 40.0),
              getOutlinedButton(appColors.armyColor(context), "Close", () {
                Navigator.pop(context);
              }),
            ],
          ),
        ),
      ),
    );
  }

  Future<bool> addUser() async {
    setState(() {
      isProcessing = true;
    });
    if (txtPhone.isEmpty) {
      showAlert(
          context, AlertDialogType.ERROR, "Error", "Please enter phone number");
      setState(() {
        isProcessing = false;
      });
      return false;
    }
    bool bResult = false;
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;
      var formData = {
        "phone": txtPhone,
        "is_admin": is_admin ? 1 : 0,
        "token": appData.dbUser['token']
      };
      var response = await dio.post(
        "createuser",
        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") {
          print("it bloody got here");
          cc.clear();

          setState(() {
            isProcessing = false;
          });
          bResult = true;
          Navigator.of(context).pop(true);
        } else {
          showAlert(
              context, AlertDialogType.ERROR, "Error", data["data"]["message"]);
        }
      }
    } catch (e) {
      print("Error: " + e.toString());
      showAlert(context, AlertDialogType.ERROR, "Error", e.toString());
    }
    setState(() {
      isProcessing = false;
    });
    return bResult;
  }
}
