import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/pages/check/health_check_record/controller.dart';
import 'package:vitalapp/pages/check/widgets/check_category_widget.dart';
import 'package:vitalapp/pages/check/widgets/configurable_card.dart';
import 'package:vitalapp/store/store.dart';

class HealthCheckDialog extends StatelessWidget {
  HealthCheckDialog({
    Key? key,
    required this.examRecord,
    required this.index,
    this.examRecordDatas,
  }) : super(key: key);

  final controller = Get.find<HealthCheckRecordController>();
  final ExamRecordDTO examRecord;
  final List<ExamRecordDataDTO>? examRecordDatas;
  final int index;
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(50),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Stack(
        children: [
          Scrollbar(
            thumbVisibility: true,
            child: SingleChildScrollView(
              child: Center(
                child: Container(
                  padding: const EdgeInsets.only(top: 50),
                  child: buildExaminationList(examRecord.batchNumber ?? ''),
                ),
              ),
            ),
          ),
          Positioned(
            right: 10,
            child: IconButton(
              icon: const Icon(Icons.close),
              onPressed: () {
                Get.back();
              },
            ),
          )
        ],
      ),
    );
  }

  Widget buildExaminationList(String batchNumber) {
    return Wrap(
      spacing: 26,
      runSpacing: 26,
      children: controller.menuList
          .map((e) => CheckCategoryWidget(
                label: e.label,
                assetName: "${e.label}.png",
                onTap: () {
                  changePage(e.value, batchNumber);
                },
              ))
          .toList(),
    );
  }

  void openConfigurableCard(String key, String batchNumber, String examData) {
    Get.dialog(
      ConfigurableCard(
        cardKey: key,
        examData: examData,
        callBack: (key, templateCode, data) async {
          await controller.updateExamByBatchNumberAsync(
            key,
            batchNumber,
            data,
          );
          return true;
        },
        patientCode: Store.user.currentSelectPatientInfo!.code,
      ),
      // transition: Transition.rightToLeft,
    );
  }

  void changePage(String key, String batchNumber) {
    List<ExamRecordDataDTO> examRecordDatas =
        controller.state.examRecordDTOList[index].examRecordDatas ?? [];

    for (ExamRecordDataDTO i in examRecordDatas) {
      if (i.key == key) {
        openConfigurableCard(key, batchNumber, i.examData ?? '');
        return;
      }
    }

    openConfigurableCard(key, batchNumber, '{}');
  }
}
