import 'dart:async';

import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/diagnosis_type.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/patient_previous_diagnosis.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/search_diagnosis.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/patient_search/patient_search_header.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/assessment/widget/empty_dropdown.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get_it/get_it.dart';
import 'package:hexcolor/hexcolor.dart';

class EditDiagnosis extends StatefulWidget {
  final PatiantInformtion patientInfo;
  final PatientPreviousDiagnosis diagnosis;

  const EditDiagnosis(
      {super.key, required this.patientInfo, required this.diagnosis});

  @override
  State<EditDiagnosis> createState() => _EditDiagnosisState();
}

class _EditDiagnosisState extends State<EditDiagnosis> {
  final TextEditingController filteredSearchController =
      TextEditingController();
  bool showAllDiagnosis = true;
  String status = '';
  String? selectedDiagnosisItem;
  String? selectedDiagnosisItemValue;
  TextEditingController remarksController = TextEditingController();
  Timer? _tTimer;
  SOAPViewModel? model;
  SearchDiagnosis? selectedDiagnosis;

  @override
  void initState() {
    super.initState();
    filteredSearchController.text = widget.diagnosis.selectedDisease ?? '';
    remarksController.text = widget.diagnosis.remarks ?? '';
    selectedDiagnosisItemValue = widget.diagnosis?.diagnosisType ?? '';
  }

  void _onTextChanged(String text) {
    if (_tTimer != null) {
      _tTimer!.cancel();
    }
    if(text.isEmpty) return;

    _tTimer = Timer(Duration(milliseconds: 500), () {
      _onStopped(text);
    });
  }

  void _onStopped(String searchText) async {
    FocusScope.of(context).unfocus();
    await model?.searchDiagnosis(widget.patientInfo, searchText);
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(onModelReady: (model) {
      this.model = model;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        model.getConditionAndType(widget.patientInfo);
        status =
            model.getConditionValue(widget.diagnosis.condition ?? '') ?? '';
      });
    }, builder: (_, model, w) {
      if (selectedDiagnosisItem == null && model.diagnosisTypeList.isNotEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            setState(() {
              selectedDiagnosisItem = model.diagnosisTypeList.keys.firstWhere(
                  (k) =>
                      model.diagnosisTypeList[k] == selectedDiagnosisItemValue,
                  orElse: () => '');
              if (selectedDiagnosisItem?.isEmpty == true)
                selectedDiagnosisItem = null;
            });
          }
        });
      }
      return AppScaffold(
        isLoading: model.state == ViewState.BusyLocal,
        isShowAppBar: true,
        appBar: PatientSearchHeader(
            title: TranslationBase.of(context).editDiagnosis),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AppText(
                  TranslationBase.of(context).editDiagnosis,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF2E303A),
                  fontSize: 16,
                ),
                SizedBox(
                  height: 16,
                ),
                AppTextFieldCustom(
                  hintText: TranslationBase.of(context).diagnosis,
                  isTextFieldHasSuffix: true,
                  hasBorder: true,
                  controller: filteredSearchController,
                  onClick: () {
                    setState(
                      () {
                        selectedDiagnosis = null;
                        filteredSearchController.text = '';
                        model.selectedIcd = '';
                      },
                    );
                  },
                  onChanged: (value) {},
                  onFieldSubmitted: () {},
                  onEditingComplete: () {
                    if (filteredSearchController.text.isEmpty) return;
                    _onStopped(filteredSearchController.text);
                  },
                  suffixIcon: IconButton(
                    icon: Icon(
                      Icons.search,
                      color: Color(0xff2B353E),
                      size: 30,
                    ),
                    onPressed: () {
                      if (filteredSearchController.text.isEmpty) return;
                      _onStopped(filteredSearchController.text);
                    },
                  ),
                ),
                Material(
                  elevation: 4.0, // Optional: for shadow effect
                  child: ConstrainedBox(
                    constraints: BoxConstraints(minHeight: 0, maxHeight: 300),
                    child: ListView.builder(
                      shrinkWrap: true,
                      itemCount: model.icdVersionList.length,
                      itemBuilder: (context, index) {
                        return ListTile(
                          title: InkWell(
                            child: AppText(model.icdVersionList[index]),
                            onTap: () {
                              setState(
                                () {
                                  selectedDiagnosis =
                                      model.findTheDiagnosisItem(
                                          model.icdVersionList[index]);
                                  filteredSearchController.text =
                                      model.icdVersionList[index];
                                  model.searchDiagnosisList.clear();
                                  model.icdVersionList.clear();
                                },
                              );
                            },
                          ),
                        );
                      },
                    ),
                  ),
                ),
                SizedBox(
                  height: 8,
                ),
                // Row(
                //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //   children: [
                //     Row(
                //       children: [
                //         Switch(
                //           value: showAllDiagnosis,
                //           activeColor: Colors.red,
                //           onChanged: (bool value) {
                //             setState(() {
                //               showAllDiagnosis = value;
                //             });
                //           },
                //         ),
                //         SizedBox(
                //           width: 8,
                //         ),
                //         AppText(
                //           TranslationBase.of(context).showAllDiagnosis,
                //           fontWeight: FontWeight.w500,
                //           color: Color(0xFF2E303A),
                //           fontSize: 11,
                //         ),
                //       ],
                //     ),
                //     SvgPicture.asset('assets/images/svgs/information.svg'),
                //   ],
                // ),
                Container(
                  margin: EdgeInsets.only(bottom: 12),
                  child: AppText(
                    TranslationBase.of(context).condition,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'Poppins',
                    fontSize: 11,
                  ),
                ),
                SizedBox(
                  width: MediaQuery.sizeOf(context).width,
                  height: 24,
                  child: ListView.builder(
                      shrinkWrap: true,
                      scrollDirection: Axis.horizontal,
                      itemCount: model.conditionTypeList.length,
                      itemBuilder: (context, index) => InkWell(
                            onTap: () {
                              setState(() {
                                status = model.conditionTypeList[index];
                              });
                            },
                            child: Row(
                              children: [
                                Container(
                                  padding: EdgeInsets.all(2.0),
                                  margin: EdgeInsets.symmetric(horizontal: 6),
                                  width: 20,
                                  height: 20,
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                        color: Colors.grey, width: 1),
                                  ),
                                  child: Container(
                                    decoration: BoxDecoration(
                                      color: status.toLowerCase() ==
                                              model.conditionTypeList[index]
                                                  .toLowerCase()
                                          ? HexColor("#D02127")
                                          : Colors.white,
                                      shape: BoxShape.circle,
                                    ),
                                  ),
                                ),
                                AppText(
                                  model.conditionTypeList[index],
                                  fontWeight: FontWeight.normal,
                                  fontFamily: 'Poppins',
                                  fontSize: SizeConfig.textMultiplier! * 1.6,
                                ),
                              ],
                            ),
                          )),
                ),
                SizedBox(
                  height: 8,
                ),
                Material(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                      side: BorderSide(
                        width: 1,
                        color: Color(0xFFEFEFEF),
                      )),
                  color: Colors.white,
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 16.0, vertical: 12),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        AppText(
                          TranslationBase.of(context).diagnoseType,
                          textAlign: TextAlign.start,
                          fontWeight: FontWeight.w600,
                          fontSize: 11,
                          color: Color(0xFF2E303A),
                        ),
                        SizedBox(
                          height: 4,
                        ),
                        model.diagnosisTypeList.isEmpty
                            ? EmptyDropDown()
                            : DropdownButtonHideUnderline(
                                child: DropdownButton(
                                  dropdownColor: Colors.white,
                                  iconEnabledColor: Colors.black,
                                  icon: Icon(Icons.keyboard_arrow_down),
                                  isExpanded: true,
                                  value: selectedDiagnosisItem == null
                                      ? model.diagnosisTypeList.keys.first
                                      : selectedDiagnosisItem,
                                  iconSize: 25,
                                  elevation: 16,
                                  onChanged: (newValue) async {
                                    if (newValue != null)
                                      setState(() {
                                        selectedDiagnosisItem = newValue;
                                        selectedDiagnosisItemValue =
                                            model.diagnosisTypeList[newValue];
                                      });
                                  },
                                  items:
                                      model.diagnosisTypeList.keys.map((item) {
                                    return DropdownMenuItem(
                                      child: AppText(
                                        item ?? '',
                                        fontSize: 14,
                                        letterSpacing: -0.96,
                                        color: AppGlobal.appTextColor,
                                        fontWeight: FontWeight.normal,
                                        textAlign: TextAlign.left,
                                      ),
                                      value: item,
                                    );
                                  }).toList(),
                                ),
                              ),
                      ],
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 8),
                  child: AppTextFieldCustom(
                    hintText: TranslationBase.of(context).remarks,
                    controller: remarksController,
                    minLines: 2,
                    maxLines: 4,
                    inputType: TextInputType.multiline,
                    onChanged: (value) {},
                    onClick: () {},
                    onFieldSubmitted: () {},
                  ),
                ),
                SizedBox(
                  height: 16,
                ),
                // InkWell(
                //   onTap: () async {
                //     if (selectedDiagnosis != null) {
                //       SearchDiagnosis? diagnosis =
                //           await model.addToFavoriteDiagnosis(widget.patientInfo,
                //               diagnosis: selectedDiagnosis);
                //       setState(() {
                //         selectedDiagnosis = diagnosis;
                //       });
                //     }
                //   },
                //   child: Row(
                //     children: [
                //       SvgPicture.asset(selectedDiagnosis?.isFavorite == true
                //           ? 'assets/images/svgs/favoriteadded.svg'
                //           : 'assets/images/svgs/favorite.svg'),
                //       SizedBox(
                //         width: 4,
                //       ),
                //       AppText(
                //         TranslationBase.of(context).addToFavorite,
                //         textAlign: TextAlign.start,
                //         fontWeight: FontWeight.w600,
                //         fontSize: 10,
                //         color: Color(0xFF449BF1),
                //       ),
                //     ],
                //   ),
                // )
              ],
            ),
          ),
        ),
        bottomNavigationBar: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(
              Radius.circular(0.0),
            ),
            border: Border.all(color: HexColor('#707070'), width: 0),
          ),
          height: SizeConfig.heightMultiplier! *
              (SizeConfig.isHeightVeryShort ? 12 : 10),
          width: double.infinity,
          child: Padding(
            padding: const EdgeInsets.all(10),
            child: Column(
              children: [
                Center(
                  child: Row(
                    children: [
                      Expanded(
                        child: AppButton(
                          title: TranslationBase.of(context).previous,
                          color: Colors.grey[300]!,
                          fontColor: Colors.black,
                          fontWeight: FontWeight.w600,
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        ),
                      ),
                      SizedBox(
                        width: 5,
                      ),
                      Expanded(
                        child: AppButton(
                            title: TranslationBase.of(context).save,
                            fontWeight: FontWeight.w600,
                            color: Color(0xFF359846),
                            onPressed: () async {
                              selectedDiagnosisItem ??=
                                  model.diagnosisTypeList.keys.first;
                              if (selectedDiagnosis == null &&
                                  filteredSearchController.text.isEmpty) {
                                DrAppToastMsg.showErrorToast(
                                    TranslationBase.of(context)
                                        .selectedDiagnosis);
                                return;
                              }
                              if (status.isEmpty) {
                                DrAppToastMsg.showErrorToast(
                                    TranslationBase.of(context)
                                        .selectConditionFirst);
                                return;
                              }

                              if (remarksController.text.isEmpty) {
                                DrAppToastMsg.showErrorToast(
                                    TranslationBase.of(context)
                                        .remarksCanNotBeEmpty);
                                return;
                              }

                              if (filteredSearchController.text ==
                                      widget.diagnosis.selectedDisease &&
                                  status.toLowerCase() ==
                                      widget.diagnosis.condition
                                          ?.toLowerCase() &&
                                  widget.diagnosis.diagnosisType ==
                                      selectedDiagnosisItemValue &&
                                  widget.diagnosis.remarks ==
                                      remarksController.text) {
                                DrAppToastMsg.showErrorToast(
                                    TranslationBase.of(context)
                                        .noChangeRecorded);
                                return;
                              }
                              widget.diagnosis.selectedDisease =
                                  filteredSearchController.text;
                              widget.diagnosis.remarks = remarksController.text;
                              widget.diagnosis.condition = model.getConditionID(status);
                              widget.diagnosis.diagnosisType =
                                  selectedDiagnosisItemValue;

                              if (selectedDiagnosis != null) {
                                widget.diagnosis.selectedCategoryCode =
                                    selectedDiagnosis?.selectedCategoryCode ??
                                        '';
                                widget.diagnosis.selectedIcdCode =
                                    selectedDiagnosis?.selectedIcdCode ?? '';
                                widget.diagnosis.selectedChapterCode =
                                    selectedDiagnosis?.selectedChapterCode ??
                                        '';
                                widget.diagnosis.selectedSectionCode =
                                    selectedDiagnosis?.selectedSectionCode ??
                                        '';
                              }

                              bool result =
                                  await model.editDiagnosis(widget.diagnosis);
                              if (result) {
                                Navigator.pop(context, result);
                              }
                            }),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      );
    });
  }
}
