import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:top_news_app/helper/helper.dart';
import '../helper/custom_appbar.dart';
import '../localization/localization.dart';
import '../main.dart';
import '../model/language.dart';
import '../repos/exception_handlers.dart';
import '../services/languages_service.dart';


class LanguagesScreen extends StatefulWidget {
  const LanguagesScreen({super.key});

  @override
  State<LanguagesScreen> createState() => _LanguagesScreenState();
}

class _LanguagesScreenState extends State<LanguagesScreen> {
  final List<Language> _languageList = [];
  final List<Color> _fontColors = [];
  final List<FontWeight> _fontWeights = [];
  final List<double> _fontSizes = [];
  final List<IconData?> _defaultIcons = [];
  final List<Color> _defaultIconColors = [];
  SharedPreferences? _prefs;
  bool isCheckedOne = false;
  bool isCheckedTwo = false;
  bool isCheckedThree = false;
  bool isCheckedFour = false;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _getLanguages();
  }

  _getLanguages() async {
    try {
      setState(() {
        _isLoading = true;
      });
      _prefs = await SharedPreferences.getInstance();
      final languagesService = LanguagesService();
      var response =
          await languagesService.getLanguagesByUserId(_prefs!.getInt('id'));
      response.forEach((languageObject) {
        var language = Language();
        language.languageId = int.parse(languageObject['id'].toString());
        language.languageName = languageObject['name'];
        language.languageCode = languageObject['code'];
        language.image = languageObject['image'];
        if (int.parse(languageObject['is_default'].toString()) == 1) {
          language.isDefault = true;
          _defaultIcons.add(Icons.check);
          _defaultIconColors.add(primaryColors);
          _fontColors.add(Colors.green);
          _fontWeights.add(FontWeight.bold);
          _fontSizes.add(20);
        } else {
          language.isDefault = false;
          _defaultIconColors.add(Colors.white);
          _defaultIcons.add(null);
          _fontWeights.add(FontWeight.normal);
          _fontColors.add(Colors.black);
          _fontSizes.add(16);
        }

        setState(() {
          _languageList.add(language);
        });
      });

      setState(() {
        _isLoading = false;
      });
    } catch ($e) {
      var message = ExceptionHandlers().getExceptionString($e);
      showMessage(message);
    }
    setState(() {
      _isLoading = false;
    });
  }

  _makeDefault(int? languageId, int? memberId, String? languageCode) async {
    try {
      setState(() {
        _isLoading = true;
      });
      _prefs = await SharedPreferences.getInstance();
      final languagesService = LanguagesService();
      var language = Language();
      language.languageId = languageId;
      language.memberId = memberId;

      language.languageCode = languageCode;
      var result = await languagesService.makeDefaultLanguage(language);
      showMessage(result['message']);
      _changeLanguage(language);
    } catch (e) {

      var message = ExceptionHandlers().getExceptionString(e);
      showMessage(message);
    }
    setState(() {
      _isLoading = false;
    });
  }

  void _changeLanguage(Language language) async {
    try {
      Locale locale = await setLocale(language.languageCode);

      Future.delayed(const Duration(milliseconds: 4), () {
        MyApp.setLocale(context, locale);
      });
    } catch (e) {
      rethrow;
    }
  }

  int counter = 0;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: customAppBar(getTranslated(context, 'Languages') ?? 'Languages','', context),
        body: _isLoading == true
            ? const Center(
                child: CircularProgressIndicator(),
              )
            : ListView(
                children: [
                  const SizedBox(
                    height: 30,
                  ),
                  SizedBox(
                    height: 95 * (_languageList.length + 1.0),
                    child: ListView.builder(
                      itemCount: _languageList.length,
                      itemBuilder: (context, index) {
                        counter++;
                        return GestureDetector(
                          onTap: () {
                            if (_languageList[index].isDefault == false) {
                              _makeDefault(
                                  _languageList[index].languageId,
                                  _prefs!.getInt('id'),
                                  _languageList[index].languageCode);
                              var indexOfIconCheck =
                                  _defaultIcons.indexOf(Icons.check);
                              var indexOfColor =
                                  _fontColors.indexOf(Colors.green);
                              var indexOfFontWeight =
                                  _fontWeights.indexOf(FontWeight.bold);
                              var indexOfFontSizes = _fontSizes.indexOf(20);

                              setState(() {
                                _languageList[indexOfIconCheck].isDefault =
                                    false;
                                _languageList[index].isDefault = true;
                                _defaultIcons[index] = Icons.check;
                                _defaultIcons[indexOfIconCheck] = null;
                                _defaultIconColors[indexOfIconCheck] =
                                    Colors.white;
                                _defaultIconColors[index] = primaryColors;
                                _fontColors[index] = Colors.green;
                                _fontColors[indexOfColor] = Colors.black;
                                _fontWeights[index] = FontWeight.bold;
                                _fontWeights[indexOfFontWeight] =
                                    FontWeight.normal;
                                _fontSizes[index] = 20;
                                _fontSizes[indexOfFontSizes] = 16;
                              });
                            }
                          },
                          child: Column(
                            children: [
                              Padding(
                                padding: const EdgeInsets.only(
                                    left: 25, right: 25, top: 20),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    SizedBox(
                                      height: 30,
                                      width: 35,
                                      child: Image.network(
                                          '${_languageList[index].image}'),
                                    ),
                                    Text(
                                      "${_languageList[index].languageName}",
                                      style: const TextStyle(
                                          fontSize: 18,
                                          fontWeight: FontWeight.normal),
                                    ),
                                    Icon(
                                      _defaultIcons[index],
                                      color: _defaultIconColors[index],
                                    )
                                  ],
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
      ),
    );
  }
}
