import 'dart:async';
import 'package:doctor_app_flutter/core/model/procedure/categories_procedure.dart';
import 'package:doctor_app_flutter/core/viewModel/procedure_View_model.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/divider_with_spaces_around.dart';
import 'package:doctor_app_flutter/widgets/shared/network_base_view.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/TextFields.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';

import '../../config/config.dart';

class EntityListCheckboxSearchWidget extends StatefulWidget {
  final ProcedureViewModel model;
  final Function addSelectedHistories;
  final Function(EntityList) removeProcedure;
  final Function(EntityList) addProcedure;
  final bool Function(EntityList) isEntityListSelected;
  final List<EntityList> masterList;
  Function(String val) selectedType;
  final bool shouldDisplaySearchField;

  EntityListCheckboxSearchWidget({
    Key? key,
    required this.model,
    required this.addSelectedHistories,
    required this.removeProcedure,
    required this.masterList,
    required this.addProcedure,
    required this.isEntityListSelected,
    required this.selectedType,
    this.shouldDisplaySearchField = true,
  }) : super(key: key);

  @override
  _EntityListCheckboxSearchWidgetState createState() => _EntityListCheckboxSearchWidgetState();
}

class _EntityListCheckboxSearchWidgetState extends State<EntityListCheckboxSearchWidget> {
  String? selectedType;
  int typeUrgent = 0;
  int typeRegular = 0;
  TextEditingController procedureName = TextEditingController();
  Timer? _debounce;
  bool _isSearching = false;

  setSelectedType(String val) {
    if (!mounted) return;
    setState(() {
      selectedType = val;
      widget.selectedType(val);
    });
  }

  List<EntityList> items = [];
  List<String> remarksList = [];
  List<int> typeList = [];

  @override
  void initState() {
    items.addAll(widget.masterList);
    super.initState();
  }

  @override
  void dispose() {
    _debounce?.cancel();
    procedureName.dispose();
    remarksController.dispose();
    super.dispose();
  }

  void _onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) _debounce!.cancel();

    _debounce = Timer(const Duration(milliseconds: 500), () {
      if (!mounted) return;

      if (query.isEmpty) {
        setState(() {
          items.clear();
          items.addAll(widget.masterList);
          _isSearching = false;
        });
      } else if (query.length >= 3) {
        setState(() {
          _isSearching = true;
        });
        widget.model.filterSearchResults(query, widget.masterList, items);
        if (mounted) {
          setState(() {
            _isSearching = false;
          });
        }
      } else {
        setState(() {
          _isSearching = false;
        });
      }
    });
  }

  TextEditingController remarksController = TextEditingController();

  Widget _buildProcedureItem(EntityList historyInfo) {
    return ExpansionTile(
      key: ValueKey('${historyInfo.procedureId}_${historyInfo.procedureName}'),
      title: Row(
        children: [
          Checkbox(
            value: widget.isEntityListSelected(historyInfo),
            activeColor: Color(0xffD02127),
            onChanged: (bool? newValue) {
              if (!mounted) return;
              setState(() {
                if (widget.isEntityListSelected(historyInfo)) {
                  widget.removeProcedure(historyInfo);
                } else {
                  widget.addProcedure(historyInfo);
                }
              });
            },
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
              child: AppText(
                Utils.convertToTitleCase(historyInfo.procedureName!),
                fontSize: 14.0,
                variant: "bodyText",
                bold: true,
                color: Color(0xff575757),
              ),
            ),
          ),
        ],
      ),
      children: [
        Container(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 11),
                      child: AppText(
                        TranslationBase.of(context).orderType,
                        fontWeight: FontWeight.w700,
                        color: Color(0xff2B353E),
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Radio(
                      activeColor: Color(0xFFD02127),
                      value: '0',
                      groupValue: historyInfo.type,
                      onChanged: (value) {
                        if (!mounted) return;
                        setState(() {
                          historyInfo.type = value.toString();
                          setSelectedType(value!);
                        });
                      },
                    ),
                    AppText(
                      'routine',
                      color: Color(0xff575757),
                      fontWeight: FontWeight.w600,
                    ),
                    Radio(
                      activeColor: Color(0xFFD02127),
                      groupValue: historyInfo.type,
                      value: '1',
                      onChanged: (value) {
                        if (!mounted) return;
                        setState(() {
                          historyInfo.type = value.toString();
                          setSelectedType(value!);
                        });
                      },
                    ),
                    AppText(
                      TranslationBase.of(context).urgent,
                      color: Color(0xff575757),
                      fontWeight: FontWeight.w600,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        SizedBox(height: 2.0),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 12.0),
          child: TextFields(
            hintText: TranslationBase.of(context).remarks,
            onChanged: (value) {
              historyInfo.remarks = value;
            },
            minLines: 3,
            maxLines: 5,
            borderWidth: 0.5,
            borderColor: Colors.grey[500]!,
          ),
        ),
        DividerWithSpacesAround(),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          NetworkBaseView(
            baseViewModel: widget.model,
            child: Container(
              height: MediaQuery.of(context).size.height * 0.75,
              child: Center(
                  child: Container(
                // margin: EdgeInsets.only(top: 15),
                decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), color: Colors.white),
                child: ListView(
                  padding: EdgeInsets.all(12),
                  children: [
                    Visibility(
                     visible: widget.shouldDisplaySearchField,
                       child:  Padding(
                          padding: const EdgeInsets.only(bottom: 12.0),
                          child: AppTextFieldCustom(
                            suffixWidget: _isSearching
                                ? Padding(
                                    padding: const EdgeInsets.all(12.0),
                                    child: SizedBox(
                                      width: 20,
                                      height: 20,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                        valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD02127)),
                                      ),
                                    ),
                                  )
                                : InkWell(
                                    onTap: () {
                                      if (procedureName.text.length >= 3) {
                                        widget.model.filterSearchResults(
                                            procedureName.text, widget.masterList, items);
                                        WidgetsBinding.instance.addPostFrameCallback((_) {
                                          // if (mounted) {
                                          //   setState(() {});
                                          // }
                                        });
                                      }
                                    },
                                    child: Icon(
                                      Icons.search,
                                      size: 25.0,
                                    ),
                                  ),
                            hintText: TranslationBase.of(context).searchProcedureHere,
                            isTextFieldHasSuffix: false,
                            maxLines: 1,
                            minLines: 1,
                            hasBorder: true,
                            controller: procedureName,
                            onChanged: (value) {
                              _onSearchChanged(value ?? '');
                            },
                            onFieldSubmitted: () {
                              if (procedureName.text.length >= 3) {
                                widget.model.filterSearchResults(
                                    procedureName.text, widget.masterList, items);
                                WidgetsBinding.instance.addPostFrameCallback((_) {
                                  if (mounted) {
                                    setState(() {});
                                  }
                                });
                              }
                            },
                          ),
                        ),
                    ),
                    if (items.isEmpty && procedureName.text.length >= 3)
                      Center(
                        child: Padding(
                          padding: const EdgeInsets.all(20.0),
                          child: AppText("Sorry, No Match", color: AppGlobal.appRedColor),
                        ),
                      )
                    else if (items.isEmpty && procedureName.text.length > 0 && procedureName.text.length < 3)
                      Center(
                        child: Padding(
                          padding: const EdgeInsets.all(20.0),
                          child: AppText("Please enter at least 3 characters to search", color: Colors.grey),
                        ),
                      )
                    else
                      ...items.map((historyInfo) => _buildProcedureItem(historyInfo)).toList(),
                  ],
                ),
              )),
            ),
          ),
          SizedBox(
            height: 10,
          ),
        ],
      ),
    );
  }
}
