import 'package:fcs/helpers/shared_pref.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/localization/transalation.dart';
import 'package:fcs/pages/main/model/language_model.dart';
import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/pages/signin/signin_page.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

class InitialLanguageSelectionPage extends StatefulWidget {
  @override
  _InitialLanguageSelectionPageState createState() =>
      _InitialLanguageSelectionPageState();
}

class _InitialLanguageSelectionPageState
    extends State<InitialLanguageSelectionPage> {
  static final List<String> languagesList = Translation().supportedLanguages;
  static final List<String> languageCodesList =
      Translation().supportedLanguagesCodes;

  final Map<dynamic, dynamic> languagesMap = {
    languagesList[0]: languageCodesList[0],
    languagesList[1]: languageCodesList[1],
  };

  String selectedLanguage;
  int selectedIndex;
  bool _isLoading;

  @override
  void initState() {
    super.initState();
    _isLoading = false;
    var languageModel = Provider.of<LanguageModel>(context, listen: false);
    this.selectedIndex = languageModel.isEng ? 0 : 1;
    loadLaunguage(languageModel);
  }

  loadLaunguage(LanguageModel languageModel) async {
    var lan = await languageModel.load();
    if (this.selectedLanguage != lan) {
      setState(() {
        this.selectedLanguage = lan;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Material(
        type: MaterialType.transparency,
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xff272282), primaryColor],
              begin: const FractionalOffset(0.8, 0.9),
              end: const FractionalOffset(0.9, 0.0),
              stops: [0.0, 1.0],
            ),
          ),
          child: Align(
            alignment: Alignment.center,
            child: SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: Column(
                children: [
                  Container(
                    height: 40,
                    child: LocalText(context, "language.selection.title",
                        fontSize: 20,
                        fontWeight: FontWeight.w200,
                        color: Colors.white),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 0),
                    child: Card(
                      color: Color(0xfff4edec),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Container(
                        padding: EdgeInsets.only(top: 20),
                        width: 300,
                        height: 160,
                        child: Column(
                            children: languagesList.asMap().entries.map((e) {
                          var language = e.value;
                          var key = e.key;
                          return InkWell(
                            onTap: () {
                              _select(key, language);
                            },
                            child: Container(
                              padding: EdgeInsets.all(2),
                              decoration: key == languagesList.length - 1
                                  ? BoxDecoration()
                                  : BoxDecoration(
                                      border: Border(
                                        bottom:
                                            BorderSide(color: Colors.grey[300]),
                                      ),
                                    ),
                              child: ListTile(
                                  leading: language == 'English'
                                      ? Container(
                                          child: CircleAvatar(
                                            radius: 20,
                                            backgroundImage: AssetImage(
                                              "icons/flags/png/gb.png",
                                              package: 'country_icons',
                                            ),
                                          ),
                                        )
                                      : Container(
                                          child: CircleAvatar(
                                            radius: 20,
                                            backgroundImage: AssetImage(
                                              "icons/flags/png/mm.png",
                                              package: 'country_icons',
                                            ),
                                          ),
                                        ),
                                  title: Text("$language"),
                                  trailing: Theme(
                                    data: Theme.of(context).copyWith(
                                      unselectedWidgetColor: Colors.grey[400],
                                    ),
                                    child: Radio(
                                      value: key,
                                      groupValue: selectedIndex,
                                      onChanged: (int i) =>
                                          _select(key, language),
                                      activeColor: primaryColor,
                                    ),
                                  )),
                            ),
                          );
                        }).toList()),
                      ),
                    ),
                  ),
                  SizedBox(height: 20.0),
                  Container(
                    padding: EdgeInsets.only(left: 230, top: 20),
                    child: Container(
                      width: 50,
                      height: 50,
                      child: InkWell(
                        onTap: () {
                          _next();
                        },
                        child: CircleAvatar(
                          radius: 25,
                          backgroundColor: Colors.white,
                          child: Center(
                              child: Icon(FontAwesomeIcons.arrowRight,
                                  color: Colors.black87)),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  _select(int index, String lang) {
    setState(() {
      selectedIndex = index;
      selectedLanguage = lang;
      Translation().onLocaleChanged(Locale(languagesMap[lang]));
      Provider.of<LanguageModel>(context, listen: false)
          .saveLanguage(selectedLanguage);
    });
  }

  _next() {
    setState(() {
      _isLoading = true;
    });
    try {
      SharedPref.finishFirstLaunch();
      bool isLogin = Provider.of<MainModel>(context, listen: false).isLogin();
      String page = isLogin ? "/home" : "/welcome";
      Navigator.of(context).pushReplacementNamed(page);
    } catch (e) {} finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
