// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/alert_dialog.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/field_layouts.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/input_text_field.dart';
import 'package:flyinsono/lab/style/lab_box_decoration.dart';
import 'package:flyinsono/utils/datetime.dart';
import 'package:get/get.dart';
import 'package:fis_theme/theme.dart';
import 'package:flyinsono/lab/components/lab_overflow_tooltip_wrapper.dart';
import 'package:flyinsono/lab/components/lab_text_tool_tip.dart';

class MedicationUsage extends StatefulWidget {
  MedicationUsage({
    super.key,
    required this.medicationUsageResultList,
  });
  List<MedicationUsageResult> medicationUsageResultList = [];

  @override
  State<MedicationUsage> createState() => _MedicationUsageState();
}

class _MedicationUsageState extends State<MedicationUsage> {
  MedicationUsageResult medicationUsageResult = MedicationUsageResult();

  @override
  void didUpdateWidget(covariant MedicationUsage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 药物使用情况
          SizedBox(
            height: 10,
          ),
          Container(
            padding: EdgeInsets.only(left: 10),
            child: Text(
              "药物使用情况：",
              style: TextStyle(
                color: LabColors.text800,
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),

          SizedBox(
            height: 10,
          ),
          Column(
            children: widget.medicationUsageResultList
                .map(
                  (e) => _buildMedicationUsageItem(e),
                )
                .toList(),
          ),
          _buildAddMedicationUsage(),
        ],
      ),
    );
  }

  Widget _buildMedicationUsageItem(MedicationUsageResult usage) {
    return Container(
      padding: EdgeInsets.all(10).copyWith(top: 0),
      margin: EdgeInsets.all(10).copyWith(top: 0),
      decoration: LabBoxDecoration.base.copyWith(
        color: LabColors.base300,
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                usage.drugName ?? '',
                style: TextStyle(
                  fontSize: 18,
                  color: LabColors.text700,
                  fontWeight: FontWeight.bold,
                ),
              ),
              IconButton(
                onPressed: () async {
                  print(usage.toJson());
                  MedicationUsageResult? result = await Get.dialog(
                    LabAlertDialog(
                      title: "编辑药物使用情况",
                      content: Container(
                        height: 260,
                        child: _buildMedicationUsage(usage),
                      ),
                      // showCancel: true,
                      onConfirm: () {
                        if (_checkMedicationUsage()) {
                          Get.back(result: medicationUsageResult);
                        }
                      },
                    ),
                    barrierColor: LabColors.base100.withOpacity(0.1),
                  );
                  if (result != null) {
                    result.updateTime = DataTimeUtils.convertToLocalString(
                      DateTime.now(),
                    );
                    int usageIndex =
                        widget.medicationUsageResultList.indexOf(usage);
                    widget.medicationUsageResultList[usageIndex] = result;
                  }
                  setState(() {});
                },
                icon: Icon(
                  Icons.edit_note,
                  color: LabColors.text700,
                ),
              )
            ],
          ),
          Row(
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                "剂量：",
                style: TextStyle(
                  fontSize: 14,
                  color: LabColors.text600,
                ),
              ),
              Expanded(
                child: Text(
                  usage.dosage ?? '',
                  style: TextStyle(
                    fontSize: 14,
                    color: LabColors.text600,
                  ),
                ),
              ),
              SizedBox(
                width: 16,
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Text(
                "备注：",
                style: TextStyle(
                  fontSize: 14,
                  color: LabColors.text600,
                ),
              ),
              Expanded(
                child: LabOverflowTooltipWrapper(
                  position: DisplayPosition.bottom,
                  offset: Offset.zero,
                  child: Text(
                    usage.remark ?? '无',
                    maxLines: 1,
                    style: TextStyle(
                      fontSize: 14,
                      color: LabColors.text600,
                      overflow: TextOverflow.ellipsis,
                      fontFamily: FTheme.ins.localeSetting.fontFamily,
                      fontFamilyFallback: [
                        FTheme.ins.data.localeSettings.chinese.fontFamily,
                      ],
                    ),
                  ),
                ),
              ),
              Text(
                usage.updateTime ?? '',
                style: TextStyle(
                  fontSize: 14,
                  color: LabColors.text600,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildAddMedicationUsage() {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        child: Center(
          child: Container(
            width: double.maxFinite,
            padding: EdgeInsets.all(10),
            margin: EdgeInsets.all(10),
            decoration: LabBoxDecoration.base.copyWith(
              color: LabColors.base300,
            ),
            child: Icon(
              Icons.add,
              color: LabColors.base500,
              size: 26,
            ),
          ),
        ),
        onTap: () async {
          MedicationUsageResult? result = await Get.dialog(
            LabAlertDialog(
              title: "新增药物使用情况",
              content: Container(
                height: 260,
                child: _buildMedicationUsage(),
              ),
              // showCancel: true,
              onConfirm: () {
                if (_checkMedicationUsage()) {
                  Get.back(result: medicationUsageResult);
                }
              },
            ),
            barrierColor: LabColors.base100.withOpacity(0.1),
          );

          if (result != null) {
            result.updateTime = DataTimeUtils.convertToLocalString(
              DateTime.now(),
            );
            widget.medicationUsageResultList.add(result);
          }
          setState(() {});
        },
      ),
    );
  }

  Widget _buildMedicationUsage([MedicationUsageResult? result]) {
    medicationUsageResult = result ?? MedicationUsageResult();
    return ListView(
      key: GlobalKey(),
      padding: EdgeInsets.all(10),
      children: [
        FieldLayout(
          layoutType: LayoutType.OOOOOOO,
          fields: [
            InputTextField(
              label: "药品名称",
              intialValue: medicationUsageResult.drugName ?? '',
              maxLines: 1,
              maxLength: 30,
              hideTextLine: true,
              onChanged: (value) {
                medicationUsageResult.drugName = value;
              },
            ),
          ],
        ),
        // SizedBox(height: 20),
        FieldLayout(
          layoutType: LayoutType.OOOOOOO,
          fields: [
            InputTextField(
              label: "使用剂量",
              intialValue: medicationUsageResult.dosage ?? '',
              maxLines: 1,
              maxLength: 20,
              hideTextLine: true,
              onChanged: (value) {
                medicationUsageResult.dosage = value;
              },
            ),
          ],
        ),
        FieldLayout(
          layoutType: LayoutType.OOOOOOO,
          fields: [
            InputTextField(
              label: "备注",
              intialValue: medicationUsageResult.remark ?? '',
              maxLines: 1,
              maxLength: 60,
              hideTextLine: true,
              onChanged: (value) {
                medicationUsageResult.remark = value;
              },
            ),
          ],
        ),
      ],
    );
  }

  // medicationUsageResult 参数非空校验
  bool _checkMedicationUsage() {
    MedicationUsageResult result = medicationUsageResult;
    if (result.drugName == null || result.drugName!.isEmpty) {
      PromptBox.toast("药品名称不能为空");
      return false;
    }
    if (result.dosage == null || result.dosage!.isEmpty) {
      PromptBox.toast("使用剂量不能为空");
      return false;
    }
    return true;
  }
}

class MedicationUsageResult {
  /// 药品名称
  String? drugName;

  /// 使用剂量
  String? dosage;

  /// 备注
  String? remark;

  String? updateTime;

  MedicationUsageResult({
    this.drugName,
    this.dosage,
    this.remark,
    this.updateTime,
  });

  MedicationUsageResult.fromJson(Map<String, dynamic> json) {
    drugName = json['drugName'];
    dosage = json['dosage'];
    remark = json['remark'];
    updateTime = json['updateTime'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['drugName'] = this.drugName;
    data['dosage'] = this.dosage;
    data['remark'] = this.remark;
    data['updateTime'] = this.updateTime;
    return data;
  }
}
