import 'dart:convert';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/api/jwt_token.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:toggle_switch/toggle_switch.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:http/http.dart' as http;

@RoutePage()
class ChangeCodePage extends StatefulWidget {
  const ChangeCodePage({Key? key}) : super(key: key);

  @override
  State<ChangeCodePage> createState() => _ChangeCodePageState();
}

class _ChangeCodePageState extends State<ChangeCodePage> {
  final SharedPreferencesManager _sharedPreferencesManager = locator<SharedPreferencesManager>();
  final ApiAuthProvider _apiAuthProvider = ApiAuthProvider();
  final JwtToken token = JwtToken();

  String current = '-';
  String destination = '-';
  bool isFirst = true;
  String imageUrl = '';

  getNewLicense(rawPid) async{
    try{imageUrl = U.decodeBase64Url(U.getBaseUrl()!) + U.decodeBase64Url(Uri.decodeComponent(U.getAccessCode()!))+'/assets/background/tn';}catch(e){}
    var pid = Uri.decodeComponent(rawPid);
    var response = await http.post(Uri.https(U.decodeBase64Url(U.getBaseUrl()!).split('//')[1], '${U.decodeBase64Url(pid)}/api/license'));
    var ver = json.decode(response.body);
    destination = ver['companyName'].isEmpty?'-':ver['companyName'];

    getInfo();
  }

  getInfo() async{
    var ver = await U.getLicense();
    setState(() {
      isFirst = false;
      current = ver['companyName'].isEmpty?'-':ver['companyName'];
    });
  }

  bool _isLoggedIn() {
    bool? isTokenExist = _sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyAccessToken);
    String? token = _sharedPreferencesManager.getString(SharedPreferencesManager.keyAccessToken);
    bool? isLoggedIn = _sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyIsLogin);

    return isLoggedIn! && isTokenExist! && token != null;
  }

  _encodeAccessCode(String ac){
    if (ac.contains('=')){
      return Uri.encodeComponent(ac);
    } else {
      return ac;
    }
  }

  @override
  Widget build(BuildContext context) {
    if(isFirst) getNewLicense(context.router.currentUrl.split('/change-code/').last);

    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          SizedBox(
            width: double.infinity, height: double.infinity,
            child: Image.network(imageUrl, fit: BoxFit.cover, width: double.infinity, height: double.infinity, errorBuilder: (context, error, stackTrace) {
              return Image.asset('assets/image/background/background.jpg', fit: BoxFit.cover, width: double.infinity, height: double.infinity);
            }),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter, end: Alignment.bottomCenter,
                colors: [
                  primaryColor.withValues(alpha: 0.50), Colors.black.withValues(alpha: 0.91)
                ]
              )
            )
          ),
          Center(
            child: Container(
              width: U.bodyWidth(context),
              padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
              child: SingleChildScrollView(
                child: Container(
                  decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(10))),
                  padding: EdgeInsets.fromLTRB(25, 20, 25, 25),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        width: double.infinity, alignment: Alignment.center,
                        child: Image(image: AssetImage('assets/image/general/AccessCode.png'), width: 250),
                      ),
                      SizedBox(height: 10),
                      Text('changeCodeMsg'.tr().replaceAll('<company_name>', destination), style: TextStyle(fontWeight: FontWeight.bold), textAlign: TextAlign.center),
                      // SizedBox(height: 15),
                      // Text('${'currentServer'.tr()}: $current', style: TextStyle(fontSize: 12), textAlign: TextAlign.left),
                      // SizedBox(height: 5),
                      // Text('${'destinationServer'.tr()}: $destination', style: TextStyle(fontSize: 12), textAlign: TextAlign.left),
                      SizedBox(height: 25),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          SizedBox(
                            height: 30, width: 100,
                            child: TextButton(
                              style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all<Color>(Colors.black12),
                                  shape: MaterialStateProperty.all<RoundedRectangleBorder>(RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)))
                              ),
                              child: Text('textCancel'.tr(), style: TextStyle(color: Colors.black, fontSize: 12)),
                              onPressed: (){
                                if (U.getAccessCode() == null) {
                                  context.router.removeLast();
                                  context.navigateToPath("/qr");
                                }
                                else{
                                  context.router.removeLast();
                                  context.navigateToPath('/app/${_encodeAccessCode(U.getAccessCode()!)}');
                                }
                              },
                            ),
                          ),
                          SizedBox(width: 10),
                          SizedBox(
                            height: 30, width: 100,
                            child: TextButton(
                              style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all<Color>(Color(0xff0D497F)),
                                  shape: MaterialStateProperty.all<RoundedRectangleBorder>(RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)))
                              ),
                              child: Text('textContinue'.tr(), style: TextStyle(color: Colors.white, fontSize: 12)),
                              onPressed: ()async{
                                var rawPid = context.router.currentUrl.split('/change-code/').last;
                                var pid = Uri.decodeComponent(rawPid);

                                try {
                                  await _sharedPreferencesManager.putString(SharedPreferencesManager.keyAccessCode, pid);
                                  await _sharedPreferencesManager.putString(SharedPreferencesManager.keySerialCode, 'P-$pid');

                                  var ver = await U.reloadLicense();
                                  await _sharedPreferencesManager.putInt(SharedPreferencesManager.version, ver['version']);

                                  if(_isLoggedIn()){
                                    var tkn = await U.getFcmToken();
                                    if (tkn == null) {
                                      token.logout();
                                      context.router.removeLast();
                                      context.navigateToPath("/app/$rawPid/login");
                                    } else {
                                      var param = {'token': tkn, 'whiteListToken': false};
                                      var res = await _apiAuthProvider.postData('/api/fcmTokens/remove/', null, param, context);
                                      if (res != null && res['success']) {
                                        token.logout();
                                        context.router.removeLast();
                                        context.navigateToPath("/app/$rawPid/login");
                                      }
                                    }
                                  }
                                  else{
                                    token.logout();
                                    context.router.removeLast();
                                    context.navigateToPath("/app/$rawPid/login");
                                  }
                                } catch(e) {
                                  print(e.toString());
                                  await _sharedPreferencesManager.clearKey(SharedPreferencesManager.keyAccessCode);
                                  await _sharedPreferencesManager.clearKey(SharedPreferencesManager.keySerialCode);
                                  await _sharedPreferencesManager.clearKey(SharedPreferencesManager.version);
                                  token.logout();
                                  context.router.removeLast();
                                  context.navigateToPath("/qr");
                                }
                              },
                            ),
                          )
                        ],
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: kIsWeb?16:50, right: 16),
            child: Align(
              alignment: Alignment.topRight,
              child: ToggleSwitch(
                minWidth: 40,
                minHeight: 30,
                cornerRadius: 20,
                initialLabelIndex: context.locale.toString() == 'en' ? 0 : 1,
                activeBgColor: [Colors.deepOrange],
                activeFgColor: Colors.white,
                inactiveBgColor: Colors.white54,
                inactiveFgColor: Colors.white,
                labels: ['EN', 'ID'],
                onToggle: (index) {
                  if (index == 0) {
                    context.setLocale(Locale('en'));
                  } else {
                    context.setLocale(Locale('id'));
                  }
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}
