import 'dart:async';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/SOAP/chief_complaint/get_chief_complaint_vida_plus.dart';
import 'package:doctor_app_flutter/core/model/SOAP/chief_complaint/search_chief_complaint_vidaplus.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/subjective/chief_complaint/widgets/complaint_items.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:flutter/material.dart';

class ComplaintSelection extends StatefulWidget {
  final List<GetChiefComplaintVidaPlus> complaints;
  final String selectedType;
  final String? firstField;
  final String? secondField;
  final String? thirdField;
  final Function(String cheifComplaint)? onSave;
  final Function(String value)? onSearch;
   final List<SearchChiefComplaint>? searchData;
  final Function(GetChiefComplaintVidaPlus)? onCrossClicked;
  const ComplaintSelection({super.key,
    required this.complaints,
    required this.selectedType,
    this.firstField,
    this.secondField,
    this.thirdField,
    this.onSave,
    this.onSearch,
    this.searchData,
    this.onCrossClicked
  });

  @override
  State<ComplaintSelection> createState() => _ComplaintSelectionState();
}

class _ComplaintSelectionState extends State<ComplaintSelection> {
  final TextEditingController firstEditingController = TextEditingController();
  final TextEditingController secondEditingController = TextEditingController();
  final TextEditingController thirdEditingController = TextEditingController();
  OverlayEntry? _overlayEntry;

  @override
  void initState() {
    super.initState();
    firstEditingController.text = widget.firstField ?? '';
    secondEditingController.text = widget.secondField ?? '';
    thirdEditingController.text = widget.thirdField ?? '';
    _focus.addListener(_onFocusChange);
  }

  void _onFocusChange() {
    removeOverlay();
  }

  void _showOverlay(BuildContext context) {
    print("the function is called");

    _overlayEntry?.remove();

    final overlay = Overlay.of(context);
    final renderBox = context.findRenderObject() as RenderBox;
    final position = renderBox.localToGlobal(Offset.zero);
    print(
        'the position is $position and render box is ${renderBox.size.height}');
    _overlayEntry = OverlayEntry(
      builder: (context) =>
          Positioned(
            left: position.dx,
            top: position.dy + renderBox.size.height - 12,
            child: Material(
              elevation: 4.0,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    SizedBox(width: MediaQuery
                        .sizeOf(context)
                        .width - 50, child: Text("Option 1"),)
                  ],
                ),
              ),
            ),
          ),
    );

    overlay?.insert(_overlayEntry!);
  }

  void removeOverlay() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
        onModelReady: (model){

    },
    builder: (_, model, w) =>  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(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            AppText(
              TranslationBase
                  .of(context)
                  .addChiefComplaint,
              fontSize: 16,
              fontWeight: FontWeight.w600,
              textAlign: TextAlign.start,
              color: Colors.black,
            ),
            ListTileTheme(
              horizontalTitleGap: 0,
              child: CheckboxListTile(
                  value: true,
                  enabled: false,
                  checkColor: Colors.white,
                  activeColor: Color(0xFFD02127),
                  side: MaterialStateBorderSide.resolveWith(
                        (Set<MaterialState> states) {
                      if (states.contains(MaterialState.selected)) {
                        return const BorderSide(color: Color(0xFFD02127));
                      }
                      return const BorderSide(color: Color(0xFFE6E6E6));
                    },
                  ),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16)),
                  controlAffinity: ListTileControlAffinity.leading,
                  onChanged: (bool? value) {},
                  title: AppText(
                    TranslationBase
                        .of(context)
                        .addChiefComplaint,
                    color: Color(0XFF575757),
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                  ),
                  contentPadding: EdgeInsets.zero),
            ),
            ListTileTheme(
              horizontalTitleGap: 0,
              child: CheckboxListTile(
                  value: true,
                  activeColor: Color(0xFFD02127),
                  checkColor: Colors.white,

                  controlAffinity: ListTileControlAffinity.leading,
                  side: MaterialStateBorderSide.resolveWith(
                        (Set<MaterialState> states) {
                      if (states.contains(MaterialState.selected)) {
                        return const BorderSide(color: Color(0xFFD02127));
                      }
                      return const BorderSide(color: Color(0xFFE6E6E6));
                    },
                  ),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16)),
                  onChanged: (bool? value) {},
                  title: AppText(
                    TranslationBase
                        .of(context)
                        .generalList,
                    color: Color(0XFF575757),
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                  ),
                  contentPadding: EdgeInsets.zero),
            ),
            ListTileTheme(
              horizontalTitleGap: 0,
              child: CheckboxListTile(
                activeColor: Color(0xFFD02127),
                checkColor: Colors.white,
                contentPadding: EdgeInsets.zero,
                side: MaterialStateBorderSide.resolveWith(
                      (Set<MaterialState> states) {
                    if (states.contains(MaterialState.selected)) {
                      return const BorderSide(color: Color(0xFFD02127));
                    }
                    return const BorderSide(color: Color(0xFFE6E6E6));
                  },
                ),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16)),
                value: false,
                controlAffinity: ListTileControlAffinity.leading,
                onChanged: (bool? value) {},
                title: AppText(
                  TranslationBase
                      .of(context)
                      .specialList,
                  color: Color(0XFF575757),
                  fontSize: 14,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
            TextWithSelectedItems(model)
          ],
        ),
      ),
    ));
  }

  FocusNode _focus = FocusNode();
  Timer? _tTimer;
  void _onStopped(String text) {
      widget.onSearch!(text);
      print(text);
  }

  void _onTextChanged(String text) {

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

    });
  }
  TextEditingController  searchController = TextEditingController();
  Widget TextWithSelectedItems(SOAPViewModel model) {
    return Material(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
          side: BorderSide(
            width: 1,
            color: Color(0xFFEFEFEF),
          )),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 8,),
          Padding(
            padding: const EdgeInsets.only(left: 8.0),
            child: AppText(TranslationBase
                .of(context)
                .enterChiefCompliants,
              fontWeight: FontWeight.w600,
              fontSize: 11,
              textAlign: TextAlign.start,
            ),
          ),
          SizedBox(
            height: 8,
          ),
          Row(
            children: [
              Expanded(
                child: Padding(
                    padding: EdgeInsets.only(left: 10, right: 10),
                    child: TextFormField(
                      autofocus: true,
                      controller: searchController,
                      textInputAction: TextInputAction.done,
                      decoration: InputDecoration(
                        hintText: '',
                        border: InputBorder.none,
                        isCollapsed: true,
                        suffixIcon: model.state == ViewState.BusyLocal
                            ? Transform.scale(
                                scale: 0.5,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                ),
                              )
                            :(searchController.text.isNotEmpty) ?IconButton(
                                icon: Icon(
                                  Icons.save_as_outlined,
                                  color: Colors.red,
                                  size: 25,
                                ),
                                onPressed: () {
                                  if(searchController.text.isNotEmpty) {
                                    widget.onSave?.call(searchController.text);
                                    searchController.text ='';
                                  }
                                }): SizedBox.shrink(),
                      ),
                      onChanged: _onTextChanged,
                      onEditingComplete: (){
                        if(searchController.text.isNotEmpty) {
                          widget.onSave?.call(searchController.text);
                          searchController.text ='';
                        }
                      },
                    )),
              )
            ],
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Material(
                elevation: 4.0, // Optional: for shadow effect
                child:
                ConstrainedBox(
                    constraints: BoxConstraints(
                        minHeight: 0,
                        maxHeight: 300),
                    child:
                    ListView.builder(
                        shrinkWrap: true,
                        itemCount: widget.searchData!.length,
                        itemBuilder: (context, index) {
                          return ListTile(

                              title: InkWell(child:AppText(widget.searchData![index].chiefComplain!), onTap:(){
                                var cc = widget.searchData![index].chiefComplain;
                                model.searchChiefComplaintList!.length =0;
                                setState((){});

                                widget.onSave!(cc!);
                                searchController.text ='';
                              }));
                        }))),
          ),

          SizedBox(
            height: 43,
            child: Row(
              children: [

                Expanded(
                  child: ListView.builder(scrollDirection: Axis.horizontal,
                      itemCount: widget.complaints.length,
                      itemBuilder: (context, index) {

                          return ComplaintItems(
                              complaint: widget.complaints[index]!,
                              isDeletable:true,
                              onCrossClicked: (complaints) {
                                widget.onCrossClicked!(complaints);
                              });
                        })
                     // }),
                ),
              ],
            ),
          ),
          SizedBox(height: 8,),
        ],
      ),
    );
  }
}
