// ignore_for_file: unnecessary_overrides, prefer_is_empty

import 'dart:io';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:IQ/app/modules/selectISP/views/select_isp_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:IQ/app/global/static_informs.dart';
import 'package:IQ/app/global/text_widget.dart';
import 'package:IQ/app/modules/selectISP/models/isp_model.dart';
import 'package:IQ/app/modules/service/api_service.dart';
import 'package:IQ/main.dart';
import 'package:IQ/app/routes/app_pages.dart';
import 'dart:convert';

class SelectISPController extends GetxController with WidgetsBindingObserver {
  late Future<List<ISPsData>?> ispListVar;
  List<ISPsData>? listOfIsps = [];
  List<ISPsData>? serversList = [];
  int selectIndex = 0;
  String errorText = '';
  bool redraw = true;

  Widget futureBuilderWidget({Widget? widget}) => FutureBuilder(
        future: ispListVar,
        builder: (
          BuildContext context,
          AsyncSnapshot<List<ISPsData>?> snapshot,
        ) {
          if (snapshot.hasData) {
            if (errorText != '') {
              return Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      errorText == 'Connection Timed Out'
                          ? Icons.wifi_find_outlined
                          : Icons.wifi_off_outlined,
                      color: Colors.white,
                      size: 35,
                    ),
                    const SizedBox(width: 15),
                    TextWidget(
                      text: errorText,
                      color: Colors.white,
                      fontWeight: FontWeight.w400,
                      fontSize: 20,
                    ),
                  ],
                ),
              );
            }
            listOfIsps = snapshot.data;
            // listOfIsps = snapshot.data?.length == 0 ? saved : snapshot.data;
            if (internetConnection) {
              if ((saved?.isNotEmpty)!) {
                var tmp = [...saved!];
                for (var i in tmp) {
                  if (i.custom == 0) {
                    saved?.remove(i);
                  }
                }
                for (var i in listOfIsps!) {
                  saved?.add(i);
                }
                serversList = saved;
                storage.write('listOfIsps', serversList);
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  if (redraw) {
                    update();
                  }
                  redraw = false;
                });
              } else {
                // saved = listOfIsps;
                serversList = listOfIsps;
                storage.write('listOfIsps', serversList);
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  if (redraw) {
                    update();
                  }
                  redraw = false;
                });
              }
            } else {
              serversList = saved;
              WidgetsBinding.instance.addPostFrameCallback((_) {
                if (redraw) {
                  update();
                }
                redraw = false;
              });
            }
            return widget!;
          } else {
            return Center(
              child: Lottie.asset(
                'assets/animated_autologin.json',
                repeat: true,
                height: 100,
                width: 100,
              ),
            );
          }
        },
      );
  final InternetConnectionChecker _internetConnectionChecker =
      InternetConnectionChecker();
  Future<bool> checkInternet() async {
    bool result = await _internetConnectionChecker.hasConnection;
    return result;
  }

  bool internetConnection = false;
  Future<List<ISPsData>?> ispList() async {
    await checkInternet().then((connection) {
      internetConnection = connection;
      return internetConnection;
    });
    if (internetConnection) {
      var value = await APIService.getUrl(
        'https://connect.snono-systems.com/index.php/api/isp',
      );
      if (value.runtimeType == int) {
        if (value == 0) {
          errorText = 'No Internet Connection';
        }
        if (value == -2) {
          errorText = 'server unreachable';
        }
        return [];
      }
      var fromJsonResponse = Isp.fromJson(jsonDecode(value.toString()));
      listOfIsps = fromJsonResponse.data;
    } else {
      listOfIsps = saved;
    }

    showNext = true;
    update();
    return listOfIsps;
  }

  initialValue() {
    if ((saved?.isNotEmpty)!) {
      initialItem = 0;
      for (var i in saved!) {
        if (i.custom == 1 || saved?.first.custom == 1) {
          isCustomIsp = true;
        } else {
          isCustomIsp = false;
        }
      }
      update();
    }
  }

  removeISP() {
    Get.defaultDialog(
      title: 'Remove ISP',
      titleStyle: buildTextStyle(
        color: brandColor,
        fontSize: 20,
        fontWeight: FontWeight.w600,
      ),
      content: TextWidget(
        text: 'Are you sure you want to remove ${selectedISP?.name} ?',
        textAlign: TextAlign.center,
        color: Colors.black,
        fontSize: 20,
      ),
      confirm: TextButton(
        onPressed: () {
          serversList?.remove(serversList?[selectIndex]);
          selectedISP = serversList?.first;
          isCustomIsp = serversList?.first.custom != 1 ? false : true;
          storage.write('listOfIsps', serversList);
          update();
          Get.back();
        },
        child: TextWidget(
          text: 'Yes',
          color: brandColor,
          fontSize: 20,
        ),
      ),
      cancel: TextButton(
        onPressed: () {
          Get.back();
        },
        child: TextWidget(
          text: 'No',
          color: brandColor,
          fontSize: 20,
        ),
      ),
    );
  }

  onSelectedItemChanged(index) {
    selectIndex = index;
    isCustomIsp = serversList![index].custom != 1 ? false : true;
    update();
  }

  onIspSelected() {
    selectedISP = serversList?[selectIndex];
    storage.write('selectedISP', selectedISP);
    url = 'https://${selectedISP?.serverAddress}/user/api/index.php/api';
    liveDataUrl =
        'http://${selectedISP?.serverAddress}/userlivetraffic/ucp/traffic?token=';

    storage.write('baseUrl', url);
    storage.write('liveDataUrl', liveDataUrl);

    update();
    Get.offNamed(Routes.AUTOLOGIN);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.inactive ||
        state == AppLifecycleState.detached ||
        state == AppLifecycleState.paused) return;
    if (state == AppLifecycleState.resumed) {
      defaultLocale = Platform.localeName.split('_')[0];
      snackBarText = 'back_twice'.tr;
    }
  }

  @override
  void onInit() {
    // ispListVar = ispList();
    // snackBarText = 'back_twice'.tr;
    // initialValue();
    // WidgetsBinding.instance.addObserver(this);
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this);
  }
}
