import 'package:auto_route/auto_route.dart';
import 'package:eitc_erm_dental_flutter/app_router.gr.dart';
import 'package:eitc_erm_dental_flutter/db_util.dart';
import 'package:eitc_erm_dental_flutter/entity/db/local_patient_info.dart';
import 'package:eitc_erm_dental_flutter/entity/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/pages/patient/vm/patient_view_model.dart';
import 'package:eitc_erm_dental_flutter/pages/patient/widget/patient_list_item.dart';
import 'package:eitc_erm_dental_flutter/widget/main_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../widget/custom_error_widget.dart';

///咨询人列表页面
@RoutePage(name: "patientListRoute")
class PatientListPage extends ConsumerStatefulWidget {
  final bool selectable;

  const PatientListPage({super.key, this.selectable = true});

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

class _PatientListPageState extends ConsumerState<PatientListPage> {
  @override
  void initState() {
    super.initState();
    ref.listenManual(patientListProvider, (p, value) {
      if (value is! AsyncData<List<PatientInfo>>) {
        return;
      }
      logd("读取到咨询人列表,开始同步本地数据");
      AsyncData<List<PatientInfo>> data = value;
      ref.read(localPatientListProvider.notifier).syncPatientList(data.value);
    });
  }

  @override
  Widget build(BuildContext context) {
    AsyncValue<List<PatientInfo>> value = ref.watch(patientListProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text(getS().patientList),
        centerTitle: true,
        forceMaterialTransparency: true,
      ),
      body: SafeArea(
          child: Padding(
        padding: EdgeInsets.fromLTRB(16.w, 12.h, 16.w, 34.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              getS().pleaseSelectPatient,
              style: context.titleMedium,
            ),
            SizedBox(
              height: 6.h,
            ),
            Expanded(child: _getListView(value)),
            SizedBox(
              height: 6.h,
            ),
            _getAddButton(value),
          ],
        ),
      )),
    );
  }

  ///获取列表
  Widget _getListView(AsyncValue<List<PatientInfo>> value) {
    return value.when(
        skipLoadingOnRefresh: false,
        data: (data) {
          return ListView.separated(
              itemBuilder: (ctx, index) {
                PatientInfo p = data[index];
                return PatientListItem(
                    index: index,
                    name: p.patientName ?? "",
                    idCard: p.identificationCard ?? "",
                    relation: p.relationship ?? getS().unknown,
                    onTap: (i) => _onSelectPatient(data[i]));
              },
              separatorBuilder: (ctx, index) => SizedBox(
                    height: 12.h,
                  ),
              itemCount: data.length);
        },
        error: (e, _) => Center(
              child: CustomErrorWidget(
                error: e,
              ),
            ),
        loading: () => Center(
              child: CircularProgressIndicator(),
            ));
  }

  ///获取添加按钮
  Widget _getAddButton(AsyncValue<List<PatientInfo>> value) {
    return switch (value) {
      AsyncData<List<PatientInfo>>() => SizedBox(
          width: double.infinity,
          child: MainButton(text: getS().addPatient, onPressed: _onAddPatient),
        ),
      _ => SizedBox(),
    };
  }

  ///当添加咨询人
  void _onAddPatient() async {
    AsyncValue<List<PatientInfo>> value = ref.read(patientListProvider);
    //咨询人数量限制4个
    if (value.value != null && value.value!.length >= 4) {
      showToast(text: getS().maxPatientCount);
      return;
    }
    bool? bo = await context.pushRoute(AddPatientRoute());
    if (bo == null || !bo) {
      return;
    }
    ref.invalidate(patientListProvider);
  }

  ///当选择咨询人
  void _onSelectPatient(PatientInfo info) async {
    if (!widget.selectable || info.appUserPatientsId.isNullOrEmpty) {
      return;
    }
    LocalPatientInfo? localInfo = await DbUtil.instance
        .getLocalPatinetByServerId(info.appUserPatientsId!);
    if (mounted) {
      Navigator.pop(context, localInfo);
    }
  }
}
