import 'package:auto_route/auto_route.dart';
import 'package:eitc_erm_dental_flutter/app_router.gr.dart';
import 'package:eitc_erm_dental_flutter/exts.dart';
import 'package:eitc_erm_dental_flutter/funcs.dart';
import 'package:eitc_erm_dental_flutter/global.dart';
import 'package:eitc_erm_dental_flutter/pages/login/vm/login_view_model.dart';
import 'package:eitc_erm_dental_flutter/pages/patient/vm/patient_view_model.dart';
import 'package:eitc_erm_dental_flutter/widget/custom_divider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../vm/global_view_model.dart';
import '../../widget/main_button.dart';

@RoutePage(name: "settingsRoute")
class SettingsPage extends ConsumerStatefulWidget {
  const SettingsPage({super.key});

  @override
  ConsumerState createState() => _SettingsPageState();
}

class _SettingsPageState extends ConsumerState<SettingsPage> {
  final List<_ListItem> _listItems = [];

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

  ///初始化列表
  void _initList() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    _listItems
      //..add(_ListItem(getS().delayShot, "", _gotoDelayShot))
      ..add(_ListItem(getS().faqs, "", _gotoFaqs))
      ..add(
          _ListItem(getS().userAgreement, "", () => gotoUserAgreement(context)))
      ..add(
          _ListItem(getS().privacyPolicy, "", () => gotoPrivacyPolicy(context)))
      ..add(_ListItem(
          getS().permissionDescription, "", () => gotoPermissionDesc(context)))
      ..add(_ListItem(getS().checkVersion,
          "${packageInfo.version}(${packageInfo.buildNumber})", _checkVersion));
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(getS().settings),
        centerTitle: true,
        forceMaterialTransparency: true,
      ),
      body: SafeArea(
          child: Column(
        children: [Expanded(child: _getListView()), _getLogoutButton()],
      )),
    );
  }

  ///列表
  Widget _getListView() {
    return ListView.separated(
        itemBuilder: (ctx, index) {
          _ListItem item = _listItems[index];
          return InkWell(
            onTap: item.onPressed,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 15.h),
              child: Row(
                children: [
                  Text(
                    item.name,
                    style: context.bodyMedium,
                  ),
                  const Spacer(),
                  item.subText.isNotEmpty
                      ? Padding(
                          padding: EdgeInsets.only(right: 10.w),
                          child: Text(item.subText),
                        )
                      : const SizedBox(),
                  const Icon(Icons.arrow_forward_ios)
                ],
              ),
            ),
          );
        },
        separatorBuilder: (ctx, index) => Padding(
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              child: const CustomDivider(
                height: 0.0,
              ),
            ),
        itemCount: _listItems.length);
  }

  //登出按钮
  Widget _getLogoutButton() {
    if (!hasToken) {
      return const SizedBox();
    }
    return SizedBox(
      width: double.infinity,
      child: Padding(
        padding: EdgeInsets.fromLTRB(16.w, 20.h, 16.w, 34.h),
        child: MainButton(text: getS().logout, onPressed: _logout),
      ),
    );
  }

  ///延迟拍摄
  void _gotoDelayShot() {
    context.pushRoute(const DelayShotSettingsRoute());
  }

  ///常见问题
  void _gotoFaqs() {
    context.pushRoute(const FaqsRoute());
  }

  ///登出
  void _logout() async {
    bool? bo = await showDialog(
        context: context,
        builder: (ctx) {
          return AlertDialog(
            title: Text(getS().hint),
            content: Text(getS().logoutHint),
            actions: [
              TextButton(
                  onPressed: () => Navigator.pop(ctx, false),
                  child: Text(getS().cancel)),
              TextButton(
                  onPressed: () => Navigator.pop(ctx, true),
                  child: Text(getS().confirm)),
            ],
          );
        });

    if (bo == null || !bo) {
      return;
    }

    logd("登出");

    await ref.read(loginProvider.notifier).logout();
    //停止检查连接
    ref.read(deviceConnectStatusProvider(videoChannel).notifier).stopCheck();
    //刷新本地就诊人列表数据
    ref.invalidate(localPatientListProvider);

    ///登出后推出所有页面,重新打开主页面
    if (mounted) {
      popAllRoutes(context);
      AutoRouter.of(context).push(const MainRoute());
    }
  }

  ///检查版本
  void _checkVersion() async {
    if (!await checkInternetWifi()) {
      return;
    }
    if (mounted) {
      if (!await checkNewVersion(context, ref)) {
        showToast(text: getS().alreadyLatestVersion);
      }
    }
  }
}

///列表条目数据
class _ListItem {
  final String name;
  final String subText;
  final VoidCallback onPressed;

  _ListItem(this.name, this.subText, this.onPressed);
}
