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/model/SOAP/assessment/FavoriteDiseaseDetails.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/diagnosis_type.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/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:hexcolor/hexcolor.dart';

List<String> patientState = ["", "Stable", "Not Stable", "Not Defined"];

class FavoriteDiagnosis extends StatefulWidget {
  final PatiantInformtion patientInfo;

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

  @override
  State<FavoriteDiagnosis> createState() => _FavoriteDiagnosisState();
}

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

  void _onTextChanged(String text) {
    if (_tTimer != null) {
      _tTimer!.cancel();
    }
    _tTimer = Timer(Duration(milliseconds: 500), () {
      _onStopped(text);
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
        onModelReady: (model) {
          this.model = model;
          WidgetsBinding.instance.addPostFrameCallback((_) {
            model.favoriteDiagnosis(widget.patientInfo);
          });
        },
        builder: (_, model, w) => AppScaffold(
          isShowAppBar: false,
          body: SingleChildScrollView(
                child: Padding(
                  padding:
                      const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      AppText(
                        TranslationBase.of(context).addDiagnosis,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF2E303A),
                        fontSize: 16,
                      ),
                      SizedBox(
                        height: 16,
                      ),
                      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).diagnosis,
                                textAlign: TextAlign.start,
                                fontWeight: FontWeight.w600,
                                fontSize: 11,
                                color: Color(0xFF2E303A),
                              ),
                              SizedBox(
                                height: 4,
                              ),
                              model.favoriteDiagnosisDetails.isEmpty
                                  ? EmptyDropDown()
                                  : DropdownButtonHideUnderline(
                                      child: DropdownButton<FavoriteDiseaseDetails>(
                                        dropdownColor: Colors.white,
                                        iconEnabledColor: Colors.black,
                                        icon: Icon(Icons.keyboard_arrow_down),
                                        isExpanded: true,
                                        itemHeight: null,
                                        value: selectedFavorite == null
                                            ? model.favoriteDiagnosisDetails.first
                                            : selectedFavorite,
                                        iconSize: 25,
                                        elevation: 16,
                                        onChanged: (newValue) async {
                                          if (newValue != null)
                                            setState(() {
                                              selectedFavorite = newValue;
                                            });
                                        },
                                        items: model.favoriteDiagnosisDetails
                                            .map((item) {
                                          return DropdownMenuItem(
                                            child: AppText(
                                              item.diseases ?? '',
                                              fontSize: 14,
                                              letterSpacing: -0.96,
                                              color: AppGlobal.appTextColor,
                                              fontWeight: FontWeight.normal,
                                              textAlign: TextAlign.left,
                                            ),
                                            value: item,
                                          );
                                        }).toList(),
                                      ),
                                    ),
                            ],
                          ),
                        ),
                      ),

                      SizedBox(
                        height: 8,
                      ),
                      Container(
                        margin: EdgeInsets.only(bottom: 12),
                        child: AppText(
                          TranslationBase.of(context).condition,
                          fontWeight: FontWeight.bold,
                          fontFamily: 'Poppins',
                          fontSize: 11,
                        ),
                      ),
                      // Row(
                      //   children: [
                      //     Expanded(
                      //         child: InkWell(
                      //       onTap: () {
                      //         setState(() {
                      //           status = "";
                      //         });
                      //       },
                      //       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 == 1
                      //                     ? HexColor("#D02127")
                      //                     : Colors.white,
                      //                 shape: BoxShape.circle,
                      //               ),
                      //             ),
                      //           ),
                      //           AppText(
                      //             TranslationBase.of(context).acute,
                      //             fontWeight: FontWeight.normal,
                      //             fontFamily: 'Poppins',
                      //             fontSize: SizeConfig.textMultiplier! * 1.6,
                      //           ),
                      //         ],
                      //       ),
                      //     )),
                      //     Expanded(
                      //       child: InkWell(
                      //         onTap: () {
                      //           setState(() {
                      //             status = "2";
                      //           });
                      //         },
                      //         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 == 2
                      //                       ? HexColor("#D02127")
                      //                       : Colors.white,
                      //                   shape: BoxShape.circle,
                      //                 ),
                      //               ),
                      //             ),
                      //             AppText(
                      //               TranslationBase.of(context).subAcute,
                      //               fontWeight: FontWeight.normal,
                      //               fontFamily: 'Poppins',
                      //               fontSize: SizeConfig.textMultiplier! * 1.6,
                      //             ),
                      //           ],
                      //         ),
                      //       ),
                      //     ),
                      //     Expanded(
                      //       child: InkWell(
                      //         onTap: () {
                      //           setState(() {
                      //             status = "3";
                      //           });
                      //         },
                      //         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 == 3
                      //                       ? HexColor("#D02127")
                      //                       : Colors.white,
                      //                   shape: BoxShape.circle,
                      //                 ),
                      //               ),
                      //             ),
                      //             AppText(
                      //               TranslationBase.of(context).chronic,
                      //               fontWeight: FontWeight.normal,
                      //               fontFamily: 'Poppins',
                      //               fontSize: SizeConfig.textMultiplier! * 1.6,
                      //             ),
                      //           ],
                      //         ),
                      //       ),
                      //     ),
                      //   ],
                      // ),
                      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 ==
                                                    model.conditionTypeList[index]
                                                ? 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,
                      ),
                    ],
                  ),
                ),
              ),
          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).cancelSmall,
                            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;
                              selectedDiagnosisItemValue = model.diagnosisTypeList[selectedDiagnosisItem];
                              selectedFavorite ??=model.favoriteDiagnosisDetails.first;

                              if(status.isEmpty){
                                DrAppToastMsg.showErrorToast(TranslationBase.of(context).selectConditionFirst);
                                return;
                              }

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

                              bool result = await model.createDiagnosisFromFavorite(
                                  widget.patientInfo,
                                  selectedFavorite,
                                  selectedDiagnosisItemValue,
                                  status,
                                  remarksController.text,
                                  false);
                              if (result) {
                                Navigator.pop(context, result);
                              }
                            },
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ));
  }
}
