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

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:naim/classes/assets.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
import 'package:naim/screens/auth/otp.dart';
import 'package:naim/widgets/input.dart';

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

class Onboarding extends StatefulWidget {
  @override
  Onboarding();
  _OnboardingState createState() => _OnboardingState();
}

class _OnboardingState extends State<Onboarding> {
  static final String path = "lib/src/pages/login/auth2.dart";
  final String backImg = camobkimg;
  String txtPhone = "";
  String initialCountry = 'NG';
  bool isProcessing = false;
  PhoneNumber number = PhoneNumber(isoCode: 'NG');

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
            image:
                DecorationImage(image: AssetImage(backImg), fit: BoxFit.cover)),
        child: Stack(
          children: <Widget>[
            Center(
              child: Container(
                margin: const EdgeInsets.all(28.0),
                padding: const EdgeInsets.symmetric(
                    horizontal: 24.0, vertical: 48.0),
                decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.8),
                    borderRadius: BorderRadius.circular(10.0)),
                child: BackdropFilter(
                  filter: ImageFilter.blur(
                    sigmaX: 1.0,
                    sigmaY: 1.0,
                  ),
                  child: SingleChildScrollView(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Container(
                            width: 200,
                            height: 200,
                            child: Image.asset(appLogo)),
                        const SizedBox(height: 10.0),
                        const Text(
                          "Nigerian Army Instant Messenger",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: armyGreen,
                              fontSize: 24.0,
                              fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(height: 20.0),
                        const Text("Please Enter Your Phone number.",
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: 18.0)),
                        const SizedBox(height: 30.0),
                        SizedBox(
                          width: double.infinity,
                          child: InternationalPhoneNumberInput(
                            onInputChanged: (PhoneNumber number) {
                              print(number.phoneNumber);
                              setState(() {
                                txtPhone = number.phoneNumber!;
                              });
                            },
                            onInputValidated: (bool value) {
                              print(value);
                            },
                            selectorConfig: const SelectorConfig(
                              selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
                            ),
                            ignoreBlank: false,
                            autoValidateMode: AutovalidateMode.disabled,
                            selectorTextStyle: TextStyle(color: Colors.black),
                            initialValue: number,
                            formatInput: false,
                            keyboardType: const TextInputType.numberWithOptions(
                                signed: true, decimal: true),
                            inputBorder: const OutlineInputBorder(
                                borderSide: BorderSide(color: armyGreen)),
                            onSaved: (PhoneNumber number) {
                              print('On Saved: $number');
                            },
                          ),
                        ),
                        const SizedBox(height: 30.0),
                        SizedBox(
                          width: double.infinity,
                          child: getElevatedButton(armyGreen,
                              isProcessing ? "Please Wait..." : "Log In", () {
                            if (!isProcessing) {
                              handleLogin();
                            }
                          }),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  handleLogin() async {
    setState(() {
      isProcessing = true;
    });
    var phone = txtPhone;
    var phoneExist = await phoneNumberExist(phone);
    if (!phoneExist) {
      showAlert(context, AlertDialogType.ERROR, "Oops",
          "Phone number does not exist in records, plesase contact admin");
      setState(() {
        isProcessing = false;
      });
      return;
    } else {
      setState(() {
        isProcessing = false;
      });
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => OtpPage(phone)));
    }
  }

  Future<bool> phoneNumberExist(String phone) async {
    print("la phone number $phone");
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;
      var formData = {"phone": phone};
      var response = await dio.post(
        "verifyphone",
        data: formData,
        options: Options(
          method: 'POST',
          contentType: "application/x-www-form-urlencoded",
          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") {
          return true;
        }
      }
    } catch (e) {
      print("Error: " + e.toString());
    }
    return false;
  }
}
