import 'package:eitc_erm_dental_flutter/entity/db/local_patient_info.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';

///切换咨询人弹窗
class SwitchPatientDialog extends ConsumerWidget {
  final void Function(LocalPatientInfo)? onSelectPatient;
  final VoidCallback onAddPatient;

  const SwitchPatientDialog(
      {super.key, required this.onSelectPatient, required this.onAddPatient});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    AsyncValue<List<LocalPatientInfo>> value =
        ref.watch(localPatientListProvider);

    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8.r), topRight: Radius.circular(8.r))),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(getS().selectPatient),
          SizedBox(
            height: 10.h,
          ),
          _getContent(value),
          SizedBox(
            height: 15.h,
          ),
          SizedBox(
            width: double.infinity,
            child: MainButton(text: getS().addPatient, onPressed: onAddPatient),
          ),
        ],
      ),
    );
  }

  Widget _getContent(AsyncValue<List<LocalPatientInfo>> value) {
    return switch (value) {
      AsyncData(value: var data) => _getList(data),
      AsyncError() => _getList([]),
      _ => CircularProgressIndicator()
    };
  }

  Widget _getList(List<LocalPatientInfo> list) {
    if (list.isEmpty) {
      return SizedBox();
    }
    return ListView.separated(
      shrinkWrap: true,
      itemBuilder: (ctx, index) {
        LocalPatientInfo info = list[index];
        return PatientListItem(
            index: index,
            name: info.name ?? "",
            idCard: info.idCardDecrypt,
            relation: info.relation ?? getS().unknown,
            onTap: (i) => onSelectPatient?.call(list[i]));
      },
      separatorBuilder: (ctx, index) => SizedBox(
        height: 10.h,
      ),
      itemCount: list.length,
    );
  }
}
