// ignore_for_file: unused_element

import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/components/checkbox_button.dart';
import 'package:vitalapp/components/dynamic_drawer.dart';
import 'package:vitalapp/components/selectBox_button.dart';
import 'package:vitalapp/consts/styles.dart';
import 'package:vitalapp/managers/contract/index.dart';
import 'package:vitalapp/pages/controllers/crowd_labels.dart';

import '../controller.dart';

/// 人群分类卡片
class CrowdLabelsCard extends GetView<PatientDetailController> {
  const CrowdLabelsCard({super.key});

  @override
  Widget build(BuildContext context) {
    return _TitleInfoCardContainer(
      title: "人群分类",
      actions: [
        Container(
          alignment: Alignment.centerRight,
          height: 30,
          child: IconButton(
            padding: EdgeInsets.zero,
            onPressed: () {
              VDynamicDrawerWrapper.show(
                scaffoldKey: controller.homeScaffoldKey,
                builder: (_) => _buildDrawer(),
              );
            },
            icon: const Icon(
              Icons.edit_note,
              color: Colors.white,
              size: 32,
            ),
          ),
        )
      ],
      titleIcon: const Icon(Icons.people, color: Colors.white),
      child: Container(
        alignment: Alignment.topLeft,
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
        child: Obx(
          () => SingleChildScrollView(
            child: Wrap(
              key: UniqueKey(),
              spacing: 16,
              runSpacing: 12,
              children: (controller.state.labelNames ?? [])
                  .map((e) => _CrowdLabelTag(name: e))
                  .toList(),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDrawer() {
    final crowdLabelsController = Get.find<CrowdLabelsController>();
    final crowdLabelsState = crowdLabelsController.state;
    List<String> selectedNormalCodes = [];
    List<String> selectedDiseaseCodes = [];
    List<String> selectedSpecialCareCodes = [];
    for (var crowdLabel in controller.state.crowdLabels!) {
      if (crowdLabelsState.normalOptions
          .map((e) => e.code)
          .toList()
          .contains(crowdLabel)) {
        selectedNormalCodes.add(crowdLabel);
      }
      if (crowdLabelsState.diseaseOptions
          .map((e) => e.code)
          .toList()
          .contains(crowdLabel)) {
        selectedDiseaseCodes.add(crowdLabel);
      }
      if (crowdLabelsState.specialCareOptions
          .map((e) => e.code)
          .toList()
          .contains(crowdLabel)) {
        selectedSpecialCareCodes.add(crowdLabel);
      }
    }
    crowdLabelsState.selectedNormalCodes = selectedNormalCodes;
    crowdLabelsState.selectedDiseaseCodes = selectedDiseaseCodes;
    crowdLabelsState.selectedSpecialCareCodes = selectedSpecialCareCodes;
    final scrollController = ScrollController();
    return VDrawer(
      width: 600,
      title: "设置人群分类",
      onConfirm: () {
        VDynamicDrawerWrapper.hide(
          scaffoldKey: controller.homeScaffoldKey,
        );
        if (selectedNormalCodes.contains("RQFL_YF")) {
          PromptBox.toast('当前居民性别为“男”，不可选择孕妇！');
          selectedNormalCodes.clear();
        }
        crowdLabelsState.selectedNormalCodes = selectedNormalCodes;
        crowdLabelsState.selectedDiseaseCodes = selectedDiseaseCodes;
        crowdLabelsState.selectedSpecialCareCodes = selectedSpecialCareCodes;
        controller.setCrowdLabelsAsync(
            crowdLabelsState.selectedCodes, crowdLabelsState.selectedNames);
      },
      child: Scrollbar(
        controller: scrollController,
        thumbVisibility: true,
        child: SingleChildScrollView(
          controller: scrollController,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 50),
            child: Column(
              children: [
                const SizedBox(height: 24),
                VSelectBoxButtonGroup<LabelDTO, String>(
                  source: crowdLabelsState.normalOptions,
                  value: crowdLabelsState.selectedNormalCodes.isNotEmpty
                      ? crowdLabelsState.selectedNormalCodes.first
                      : '',
                  labelGetter: (LabelDTO data) => data.labelName!,
                  valueGetter: (LabelDTO data) => data.code!,
                  onChanged: (value) {
                    selectedNormalCodes.clear();
                    if (value != null) {
                      selectedNormalCodes.add(value);
                    }
                  },
                ),
                const SizedBox(height: 8),
                Divider(
                  indent: 32,
                  endIndent: 32,
                  thickness: 1,
                  color: Colors.grey.shade300,
                ),
                const SizedBox(height: 8),
                VCheckBoxButtonGroup<LabelDTO, String>(
                  source: crowdLabelsState.diseaseOptions,
                  values: crowdLabelsState.selectedDiseaseCodes,
                  labelGetter: (LabelDTO data) => data.labelName!,
                  valueGetter: (LabelDTO data) => data.code!,
                  onChanged: (value) {
                    selectedDiseaseCodes = value;
                  },
                ),
                const SizedBox(height: 8),
                Divider(
                  indent: 32,
                  endIndent: 32,
                  thickness: 1,
                  color: Colors.grey.shade300,
                ),
                const SizedBox(height: 8),
                VCheckBoxButtonGroup<LabelDTO, String>(
                  source: crowdLabelsState.specialCareOptions,
                  values: crowdLabelsState.selectedSpecialCareCodes,
                  labelGetter: (LabelDTO data) => data.labelName!,
                  valueGetter: (LabelDTO data) => data.code!,
                  onChanged: (value) {
                    selectedSpecialCareCodes = value;
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

/// 最近检测记录
class LatestRecordCard extends GetView<PatientDetailController> {
  const LatestRecordCard({super.key});

  @override
  Widget build(BuildContext context) {
    final state = controller.state;
    final ContractUtils contractUtils = ContractUtils();

    return _TitleInfoCardContainer(
      title: "最近检测记录",
      titleIcon: const Icon(Icons.tips_and_updates, color: Colors.white),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
        child: Column(
          children: const [],
        ),
      ),
    );
  }

  Widget _buildItem(String label, String content) {
    return SizedBox(
      height: 30,
      child: Row(
        children: [
          Text(
            label,
            style: const TextStyle(color: Colors.grey, fontSize: 18),
          ),
          const SizedBox(width: 12),
          Text(
            content,
            style: const TextStyle(color: Colors.black, fontSize: 18),
          ),
        ],
      ),
    );
  }
}

/// 签约信息卡片
class FollowupTipsCard extends GetView<PatientDetailController> {
  const FollowupTipsCard({super.key});

  @override
  Widget build(BuildContext context) {
    final state = controller.state;
    final ContractUtils contractUtils = ContractUtils();

    return _TitleInfoCardContainer(
      title: "签约信息",
      titleIcon: const Icon(Icons.tips_and_updates, color: Colors.white),
      // titleBgColor: Colors.yellow.shade900,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
        child: Column(
          children: [
            _buildItem(
              "签约状态",
              contractUtils.contractStateTransition(state.contractState),
            ),
            _buildItem(
                "签约医生",
                state.contractState != ContractStateEnum.Signed
                    ? ""
                    : state.contractedDoctorName),
            // _buildItem("签约日期", '2023-10-12'),
          ],
        ),
      ),
    );
  }

  Widget _buildItem(String label, String content) {
    return SizedBox(
      height: 30,
      child: Row(
        children: [
          Text(
            label,
            style: const TextStyle(color: Colors.grey, fontSize: 18),
          ),
          const SizedBox(width: 12),
          Text(
            content,
            style: const TextStyle(color: Colors.black, fontSize: 18),
          ),
        ],
      ),
    );
  }
}

class _TitleInfoCardContainer extends StatelessWidget {
  final Widget child;
  final String title;
  final Widget? titleIcon;
  final Color? titleBgColor;
  final List<Widget>? actions;

  const _TitleInfoCardContainer({
    required this.child,
    required this.title,
    this.titleIcon,
    this.titleBgColor,
    this.actions,
  });

  @override
  Widget build(BuildContext context) {
    Widget titleWidget = Text(
      title,
      style: const TextStyle(color: Colors.white, fontSize: 20),
    );
    if (titleIcon != null) {
      titleWidget = Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          titleIcon!,
          const SizedBox(width: 8),
          titleWidget,
          if (actions != null)
            Expanded(
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.end,
                children: actions!,
              ),
            ),
        ],
      );
    }
    return Container(
      alignment: Alignment.topLeft,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: GlobalStyles.borderRadius,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  // Color.fromRGBO(59, 188, 255, 1),
                  // Color.fromRGBO(44, 120, 229, 1),
                  Theme.of(context).primaryColor,
                  Theme.of(context).primaryColor.withOpacity(.6),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              // color: titleBgColor ?? Theme.of(context).primaryColor,
              borderRadius: const BorderRadius.only(
                topLeft: GlobalStyles.borderRadiusValue,
                topRight: GlobalStyles.borderRadiusValue,
              ),
            ),
            child: titleWidget,
          ),
          Expanded(
            child: Container(
              alignment: Alignment.topLeft,
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              child: child,
            ),
          ),
        ],
      ),
    );
  }
}

class _CrowdLabelTag extends StatelessWidget {
  final String name;
  final String? code;
  final ValueChanged<String?>? onTap;
  final Color? backgroundColor;

  const _CrowdLabelTag({
    required this.name,
    this.onTap,
    this.backgroundColor,
    this.code,
  });

  @override
  Widget build(BuildContext context) {
    final color =
        backgroundColor ?? Theme.of(context).primaryColor.withOpacity(.6);
    return Material(
      child: InkWell(
        borderRadius: GlobalStyles.borderRadius,
        onTap: onTap != null ? () => onTap!.call(code) : null,
        child: IntrinsicWidth(
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: 100),
            child: Container(
              alignment: Alignment.center,
              height: 32,
              decoration: BoxDecoration(
                color: color,
                borderRadius: GlobalStyles.borderRadius,
              ),
              child: Text(
                name,
                style: const TextStyle(color: Colors.white, fontSize: 14),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
