import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:eitc_erm_dental_flutter/app_router.gr.dart';
import 'package:eitc_erm_dental_flutter/dialog/app_start_agreement_dialog.dart';
import 'package:eitc_erm_dental_flutter/dialog/switch_patient_dialog.dart';
import 'package:eitc_erm_dental_flutter/entity/db/local_patient_info.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/main/widget/connected_view.dart';
import 'package:eitc_erm_dental_flutter/pages/main/widget/unconnected_view.dart';
import 'package:eitc_erm_dental_flutter/pages/patient/vm/patient_view_model.dart';
import 'package:eitc_erm_dental_flutter/pages/patient/widget/patient_info_bar.dart';
import 'package:eitc_erm_dental_flutter/vm/global_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

///主页面
@RoutePage(name: "mainRoute")
class MainPage extends ConsumerStatefulWidget {
  const MainPage({super.key});

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

class _MainPageState extends ConsumerState<MainPage> {
  ///最后退出时间
  DateTime? lastExitTime;

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

    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(deviceConnectStatusProvider(videoChannel).notifier).startCheck();
    });
  }

  @override
  void dispose() {
    if (context.mounted) {
      ref.read(deviceConnectStatusProvider(videoChannel).notifier).stopCheck();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bool isConnected = ref.watch(deviceConnectStatusProvider(videoChannel));
    return PopScope(
        canPop: !Platform.isAndroid,
        onPopInvokedWithResult: _onPopInvoke,
        child: Scaffold(
          appBar: _getAppBar(),
          body: SafeArea(
            child: Column(
              children: [
                PatientInfoBar(
                  onSwitchPatient: _onSwitchPatient,
                  onAddPatient: _onAddPatient,
                ),
                Expanded(
                    child: isConnected
                        ? ConnectedView(
                            startVideo: _startVideo,
                          )
                        : const UnconnectedView())
              ],
            ),
          ),
        ));
  }

  void _onPopInvoke(bool didPop, dynamic result) {
    if (didPop) {
      return;
    }
    DateTime now = DateTime.now();
    if (lastExitTime == null ||
        now.millisecondsSinceEpoch - lastExitTime!.millisecondsSinceEpoch >
            2000) {
      lastExitTime = now;
      showToast(text: getS().tapAgainExit);
    } else {
      exitApp();
    }
  }

  AppBar _getAppBar() {
    Color color = context.onSurfaceVariantColor;
    ButtonStyle buttonStyle = ButtonStyle(
        padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 5.w)));
    TextStyle textStyle = TextStyle(fontSize: 12.sp, color: color);
    return AppBar(
      automaticallyImplyLeading: false,
      forceMaterialTransparency: true,
      actions: [
        TextButton(
            onPressed: _gotoHistories,
            style: buttonStyle,
            child: Row(children: [
              Icon(
                Icons.people_outline,
                color: color,
                size: 24.r,
              ),
              SizedBox(
                width: 4.w,
              ),
              Text(
                getS().serviceCenter,
                style: textStyle,
              )
            ])),
        TextButton(
          onPressed: _gotoSettings,
          style: buttonStyle,
          child: Row(
            children: [
              Icon(
                Icons.settings_outlined,
                color: color,
                size: 24.r,
              ),
              SizedBox(
                width: 4.w,
              ),
              Text(getS().settings, style: textStyle),
            ],
          ),
        ),
        SizedBox(
          width: 12.w,
        ),
      ],
    );
  }

  ///前往历史记录
  void _gotoHistories() {
    context.pushRoute(const HistoryRoute());
  }

  ///前往设置
  void _gotoSettings() {
    context.pushRoute(const SettingsRoute());
  }

  ///开始视频
  void _startVideo() async {
    //正在同步就诊人数据
    if (isSyncingPatient) {
      showToast(text: getS().syncDataWaiting);
      return;
    }
    //已选择的就诊人ID
    if (selectedPatientId < 0) {
      showToast(text: getS().pleaseSelectPatient);
      return;
    }
    context.pushRoute(VideoViewRoute());
  }

  ///当切换咨询人
  void _onSwitchPatient() {
    if (context.mounted) {
      showModalBottomSheet(
          context: context,
          builder: (ctx) {
            return SwitchPatientDialog(onSelectPatient: (info) {
              Navigator.pop(ctx);
              _onSelectPatient(info);
            }, onAddPatient: () {
              Navigator.pop(ctx);
              _onAddPatient();
            });
          });
    }
  }

  ///当选择了咨询人
  void _onSelectPatient(LocalPatientInfo info) {
    logd("选择了咨询人,$info");
    //记录选择的就诊人ID
    setSelectedPatientId(info.id);
    ref.invalidate(localPatientListProvider);
  }

  ///当添加咨询人
  void _onAddPatient() async {
    if (!await checkInternetWifi()) {
      logd("新增咨询人,但是连的是设备");
      return;
    }
    if (mounted) {
      if (!checkLogin(context)) {
        return;
      }
      logd("新增咨询人,打开咨询人列表页面");
      LocalPatientInfo? info = await context.pushRoute(PatientListRoute());
      if (info != null) {
        _onSelectPatient(info);
      }
    }
  }
}
