import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/sc_debounce_widget.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/shared/data_sources/models/country_mode.dart';
import 'package:provider/provider.dart';

import 'package:yumi/ui_kit/components/appbar/socialchat_appbar.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/ui_kit/components/custom_cached_image.dart';
import 'package:yumi/ui_kit/theme/socialchat_theme.dart';
import 'package:yumi/shared/business_logic/models/res/country_res.dart';
import 'package:yumi/services/general/sc_app_general_manager.dart';
import 'package:yumi/services/auth/user_profile_manager.dart';

import '../../app/constants/sc_global_config.dart';
import '../../app/config/business_logic_strategy.dart';

///国家
class CountryPage extends StatefulWidget {
  bool isDialog = false;

  CountryPage({this.isDialog = false});

  @override
  _CountryPageState createState() => _CountryPageState(isDialog);
}

class _CountryPageState extends State<CountryPage> {
  bool isDialog = false;
  Country? selectCountryInfo;

  _CountryPageState(this.isDialog);

  @override
  void initState() {
    super.initState();
    Provider.of<SCAppGeneralManager>(context, listen: false).fetchCountryList();
  }

  @override
  void dispose() {
    Provider.of<SCAppGeneralManager>(
      context,
      listen: false,
    ).clearCountrySelection();
    super.dispose();
  }

  /// 获取业务逻辑策略
  BusinessLogicStrategy get _strategy => SCGlobalConfig.businessLogicStrategy;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        widget.isDialog
            ? Container()
            : Image.asset(
              "sc_images/splash/sc_splash.png",
              width: ScreenUtil().screenWidth,
              height: ScreenUtil().screenHeight,
              fit: BoxFit.cover,
            ),
        Scaffold(
          backgroundColor:
              widget.isDialog
                  ? _strategy.getCountryPageScaffoldBackgroundColor()
                  : Colors.transparent,
          resizeToAvoidBottomInset: false,
          appBar:
              widget.isDialog
                  ? null
                  : SocialChatStandardAppBar(
                    title: SCAppLocalizations.of(context)!.countryRegion,
                    onTag: () {
                      Provider.of<SCAppGeneralManager>(
                        context,
                        listen: false,
                      ).clearCountrySelection();
                      SCNavigatorUtils.goBack(context);
                    },
                    actions: [
                      Consumer<SCAppGeneralManager>(
                        builder: (_, provider, __) {
                          return Container(
                            margin: EdgeInsets.only(right: 20.w),
                            child: SCDebounceWidget(
                              onTap: () {
                                if (selectCountryInfo != null) {
                                  Provider.of<SocialChatUserProfileManager>(
                                    context,
                                    listen: false,
                                  ).setCountry(selectCountryInfo!);
                                  provider.updateCurrentCountry(
                                    selectCountryInfo,
                                  );
                                  SCNavigatorUtils.goBack(context);
                                }
                              },
                              child: Image.asset(
                                selectCountryInfo != null
                                    ? _strategy.getCountrySelectOkIcon()
                                    : _strategy.getCountrySelectUnOkIcon(),
                                width: 38.w,
                                height: 22.w,
                              ),
                            ),
                          );
                        },
                      ),
                    ],
                  ),
          body: SafeArea(
            top: false,
            child: Column(
              children: [
                widget.isDialog ? SizedBox(height: 10.w) : Container(),
                widget.isDialog
                    ? Row(
                      children: [
                        SCDebounceWidget(
                          child: Container(
                            width: 50.w,
                            height: 30.w,
                            alignment: AlignmentDirectional.centerStart,
                            margin: EdgeInsetsDirectional.only(start: 10.w),
                            child: Icon(
                              SCGlobalConfig.lang == "ar"
                                  ? Icons.keyboard_arrow_right
                                  : Icons.keyboard_arrow_left,
                              size: 28.w,
                              color: _strategy.getCountryPageIconColor(),
                            ),
                          ),
                          onTap: () {
                            Provider.of<SCAppGeneralManager>(
                              context,
                              listen: false,
                            ).clearCountrySelection();
                            SmartDialog.dismiss(tag: "showCountryPage");
                          },
                        ),
                        Spacer(),
                        Consumer<SCAppGeneralManager>(
                          builder: (_, provider, __) {
                            return Container(
                              margin: EdgeInsets.only(right: 20.w),
                              child: SCDebounceWidget(
                                onTap: () {
                                  if (selectCountryInfo != null) {
                                    Provider.of<SocialChatUserProfileManager>(
                                      context,
                                      listen: false,
                                    ).setCountry(selectCountryInfo!);
                                    provider.updateCurrentCountry(
                                      selectCountryInfo,
                                    );
                                    SmartDialog.dismiss(tag: "showCountryPage");
                                  }
                                },
                                child: Image.asset(
                                  selectCountryInfo != null
                                      ? _strategy.getCountrySelectOkIcon()
                                      : _strategy.getCountrySelectUnOkIcon(),
                                  width: 38.w,
                                  height: 22.w,
                                ),
                              ),
                            );
                          },
                        ),
                      ],
                    )
                    : Container(),
                widget.isDialog
                    ? Row(
                      children: [
                        SizedBox(width: 15.w),
                        text(
                          SCAppLocalizations.of(context)!.selectYourCountry,
                          textColor: _strategy.getCountryPagePrimaryTextColor(),
                          fontSize: 16.sp,
                        ),
                      ],
                    )
                    : Container(),
                widget.isDialog ? SizedBox(height: 12.w) : Container(),
                Expanded(
                  child: Consumer<SCAppGeneralManager>(
                    builder: (_, provider, __) {
                      return ListView.separated(
                        itemCount: provider.countryModeList.length, // 列表项数量
                        padding: EdgeInsets.only(bottom: 15.w),
                        itemBuilder: (context, index) {
                          return _buildCountryItem(
                            index,
                            provider.countryModeList[index],
                            provider,
                          );
                        },
                        separatorBuilder: (BuildContext context, int index) {
                          return SizedBox(height: 10.w);
                        },
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildCountryItem(
    int subIndex,
    CountryMode countryModeList,
    SCAppGeneralManager provider,
  ) {
    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(left: 25.w),
          alignment: Alignment.centerLeft,
          child: text(
            countryModeList.prefix,
            textColor:
                widget.isDialog
                    ? _strategy.getCountryPageSecondaryTextColor()
                    : Colors.white,
            fontSize: 15.sp,
          ),
        ),
        SizedBox(height: 5.w),
        Container(
          margin: EdgeInsets.symmetric(horizontal: 15.w),
          padding: EdgeInsets.symmetric(vertical: 8.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            color: _strategy.getCountryPageContainerBackgroundColor(),
            border: Border.all(
              color: _strategy.getCountryItemBorderColor(),
              width: 1.w,
            ),
          ),
          child: Column(
            spacing: 3.w,
            children: List.generate(countryModeList.prefixCountrys.length, (
              cIndex,
            ) {
              Country country = countryModeList.prefixCountrys[cIndex];
              return Row(
                children: [
                  SizedBox(width: 15.w),
                  CustomCachedImage(
                    imageUrl: country.nationalFlag ?? "",
                    width: 28.w,
                    height: 19.w,
                  ),
                  SizedBox(width: 5.w),
                  Expanded(
                    child: text(
                      country.aliasName ?? "",
                      textColor: _strategy.getCountryPagePrimaryTextColor(),
                      fontSize: 15.sp,
                    ),
                  ),
                  GestureDetector(
                    child: Container(
                      color: Colors.transparent,
                      padding: EdgeInsets.all(8.w),
                      child: Image.asset(
                        selectCountryInfo?.id == country.id
                            ? _strategy.getCountryRadioSelectedIcon()
                            : _strategy.getCountryRadioUnselectedIcon(),
                        width: 16.w,
                        color:
                            selectCountryInfo?.id != country.id
                                ? Colors.black38
                                : null,
                        height: 16.w,
                      ),
                    ),
                    onTap: () {
                      selectCountryInfo = provider.chooseCountry(
                        subIndex,
                        cIndex,
                      );
                      setState(() {});
                    },
                  ),
                ],
              );
            }),
          ),
        ),
      ],
    );
  }
}
