import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/pages/remedical/create_check/state.dart';
import 'package:flyinsono/pages/remedical/edit_patient_dialog/widgets/date_time.dart';
import 'package:get/get.dart';
import 'package:universal_html/html.dart' as html;
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_jsonrpc/rpc.dart';

class PatientAgeInput extends FStatefulWidget implements FPage {
  final PatientInfo patientInfo;

  PatientAgeInput(this.patientInfo);

  @override
  FState<FStatefulWidget> createState() {
    return _PatientAgeInputState();
  }

  @override
  String get pageName => "PatientAgeInput";
}

class _PatientAgeInputState extends FState<PatientAgeInput> {
  static const C_AGE_TYPE = [
    'Year',
    'YearAndMonth',
    'MonthAndWeek',
    'WeekAndDay',
  ];
  final languageConfigManager = Get.find<ILanguageConfigManager>();

  @override
  FWidget build(BuildContext context) {
    return FRow(
      children: [
        FContainer(
          width: i18nBook.isCurrentChinese ? 80 : 130,
          child: FText(
            i18nBook.remedical.age.t,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        FExpanded(
          child: _buildAgeType(
            widget.patientInfo.ageUnits,
          ),
        ),
        FExpanded(
          child: _buildAgeTypeSelect(),
        )
      ],
    );
  }

  FWidget _buildAgeType(String? currentAgeType) {
    switch (currentAgeType ?? 'Year') {
      case 'YearAndMonth':
        return _buildYearAndMonth();
      case 'MonthAndWeek':
        return _buildMonthAndWeek();
      case 'WeekAndDay':
        return _buildWeekAndDay();
      default:
        return _buildYear();
    }
  }

  FWidget _buildYear() {
    return FContainer(
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              widget.patientInfo.ageUnits = 'Year';
              widget.patientInfo.ageYear = value;
              widget.patientInfo.birthday =
                  FmtedDuration.countDurYearAndMonthBirthDay(value);
            },
            widget.patientInfo.ageYear,
            [FilteringTextInputFormatter.digitsOnly],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.years.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildYearAndMonth() {
    return FContainer(
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              widget.patientInfo.ageYear = value;
              widget.patientInfo.birthday =
                  FmtedDuration.countDurYearAndMonthBirthDay(
                      value, widget.patientInfo.ageMonth ?? '');
            },
            widget.patientInfo.ageYear,
            [FilteringTextInputFormatter.digitsOnly],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.years.t),
          _buildSizedBox(),
          _buildAgeTypeInput(
            (value) {
              widget.patientInfo.ageMonth = value;
              widget.patientInfo.birthday =
                  FmtedDuration.countDurYearAndMonthBirthDay(
                      widget.patientInfo.ageYear ?? '', value);
            },
            widget.patientInfo.ageMonth,
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^(0?[1-9]|1[0-1])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.month.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildSizedBox() {
    return const FSizedBox(
      width: 5,
    );
  }

  FWidget _buildMonthAndWeek() {
    return FContainer(
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              widget.patientInfo.ageMonth = value;
              widget.patientInfo.birthday =
                  FmtedDuration.countDurMonthAndWeekBirthDay(
                      value, widget.patientInfo.ageWeek ?? '');
            },
            widget.patientInfo.ageMonth,
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^(0?[1-9]|1[0-1])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.month.t),
          _buildSizedBox(),
          _buildAgeTypeInput(
            (value) {
              widget.patientInfo.ageWeek = value;
              widget.patientInfo.birthday =
                  FmtedDuration.countDurMonthAndWeekBirthDay(
                      widget.patientInfo.ageMonth ?? '', value);
            },
            widget.patientInfo.ageWeek,
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^([0-4])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.week.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildWeekAndDay() {
    return FContainer(
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              widget.patientInfo.ageWeek = value;
              widget.patientInfo.birthday =
                  FmtedDuration.countDurWeekAndDayBirthDay(
                      value, widget.patientInfo.ageDay ?? '');
            },
            widget.patientInfo.ageWeek,
            [FilteringTextInputFormatter.digitsOnly],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.week.t),
          _buildSizedBox(),
          _buildAgeTypeInput(
            (value) {
              widget.patientInfo.ageDay = value;
              widget.patientInfo.birthday =
                  FmtedDuration.countDurWeekAndDayBirthDay(
                      widget.patientInfo.ageWeek ?? '', value);
            },
            widget.patientInfo.ageDay,
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^([1-9]|[1-2]\d|3[0-1])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.day.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildAgeTypeInput(Function(dynamic)? onChanged, String? text,
      [List<TextInputFormatter>? inputFormatters]) {
    return FBorderInput(
      maxLength: 20,
      borderColor: const Color.fromRGBO(230, 230, 230, 1),
      height: 38,
      contentSize: 16,
      onChanged: (value) => onChanged?.call(value),
      controller: TextEditingController(
        text: text,
      ),
      inputFormatters: inputFormatters,
    );
  }

  FWidget _buildAgeTypeSelect() {
    void onSelectChanged(String? value, int? index) {
      PatientInfo currentPatient = widget.patientInfo;
      setState(() {
        currentPatient.ageUnits = value;
      });
      bool hasBirthDay = widget.patientInfo.birthday != null &&
          (widget.patientInfo.birthday?.isNotEmpty ?? false);
      switch (value ?? 'Year') {
        case 'YearAndMonth':
          if (hasBirthDay) {
            currentPatient.ageYear = FmtedDuration.countDurYearAndMonth(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[0]
                .toString();
            currentPatient.ageMonth = FmtedDuration.countDurYearAndMonth(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[1]
                .toString();
          }

          break;
        case 'MonthAndWeek':
          if (hasBirthDay) {
            currentPatient.ageMonth = FmtedDuration.countDurMonthAndWeek(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[0]
                .toString();
            currentPatient.ageWeek = FmtedDuration.countDurMonthAndWeek(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[1]
                .toString();
          }
          break;
        case 'WeekAndDay':
          if (hasBirthDay) {
            currentPatient.ageWeek = FmtedDuration.countDurWeekAndDay(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[0]
                .toString();
            currentPatient.ageDay = FmtedDuration.countDurWeekAndDay(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[1]
                .toString();
          }
          break;
        default:
          if (hasBirthDay) {
            currentPatient.ageYear = FmtedDuration.countDurYearAndMonth(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[0]
                .toString();
          }
          break;
      }
    }

    String ageUnits = widget.patientInfo.ageUnits ?? 'Year';
    if (ageUnits.isEmpty) {
      ageUnits = 'Year';
    }
    final select = FSelect<SelectModel, String>(
      source: getAgeType(),
      value: ageUnits,
      clearable: false,
      fontFamily: FTheme.ins.localeSetting.fontFamily,
      height: 38,
      optionLabelExtractor: (data) => data.name,
      optionValueExtractor: (data) => data.code,
      onSelectChanged: (value, index) {
        onSelectChanged(value, index);
      },
    );
    return select;
  }

  List<SelectModel> getAgeType() {
    List<SelectModel> selectList = [];
    for (int i = 0; i < C_AGE_TYPE.length; i++) {
      selectList.add(
        SelectModel(
          name: languageConfigManager.getExamLanguageValue(
            C_AGE_TYPE[i],
          ),
          code: C_AGE_TYPE[i],
        ),
      );
    }
    return selectList;
  }
}
