import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/oracle_code_provider.dart';
import 'package:test_sa/controllers/providers/api/parts_provider.dart';
import 'package:test_sa/controllers/providers/api/search_user_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/new_models/asset_nd_auto_complete_by_dynamic_codes_model.dart';
import 'package:test_sa/models/new_models/users_based_on_search_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/views/app_style/sizing.dart';

import '../../../extensions/text_extensions.dart';
import '../../../models/service_request/spare_parts.dart';
import '../../../new_views/app_style/app_text_style.dart';

class SearchUserAutoCompleteField extends StatefulWidget {
  final String initialValue;
  final num? assetId;
  final bool clearAfterPick, byName;
  final Function(UsersBasedOnSearchModel) onPick;

  const SearchUserAutoCompleteField({Key? key, required this.byName, required this.initialValue, this.assetId, required this.onPick, this.clearAfterPick = true}) : super(key: key);

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

class _UsersAutoCompleteFieldState extends State<SearchUserAutoCompleteField> {
  late UserSearchProvider _TechnologyUsersProvider;

  late TextEditingController _controller;

  bool loading = false;

  @override
  void initState() {
    _controller = TextEditingController(text: widget.initialValue);
    super.initState();
    _TechnologyUsersProvider = Provider.of<UserSearchProvider>(context, listen: false);
  }

  @override
  void didUpdateWidget(covariant SearchUserAutoCompleteField oldWidget) {
    if (widget.initialValue != oldWidget.initialValue) {
      _controller = TextEditingController(text: widget.initialValue);
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final border = UnderlineInputBorder(borderSide: BorderSide.none, borderRadius: BorderRadius.circular(16));
    return Container(
      decoration: BoxDecoration(
        color: AppColor.background(context),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColor.border2Color(context)),
        //  boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
      ),
      child: Autocomplete<UsersBasedOnSearchModel>(
        optionsBuilder: (TextEditingValue textEditingValue) async {
          if (textEditingValue.text.isEmpty) {
            if (loading) {
              setState(() {
                loading = false;
              });
            }
            return const Iterable<UsersBasedOnSearchModel>.empty();
          }
          if (!loading) {
            setState(() {
              loading = true;
            });
          }
          List<UsersBasedOnSearchModel> workOrders = (await _TechnologyUsersProvider.getUsersBasedOnSearch(context.userProvider.user!.clientId!, textEditingValue.text));
          setState(() {
            loading = false;
          });
          return workOrders;
        },
        displayStringForOption: (UsersBasedOnSearchModel option) => widget.byName ? "${option.userName ?? "-"} (Nurse)" ?? "" : option.employeeId ?? "",
        fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) {
          return TextField(
            controller: _controller,
            focusNode: fieldFocusNode,
            style: TextStyle(fontWeight: FontWeight.w500, fontSize: context.isTablet() ? 16 : 14, color: AppColor.textStyleColor(context)),
            cursorColor: AppColor.loadingColor(context),
            textAlign: TextAlign.start,
            decoration: InputDecoration(
              border: border,
              disabledBorder: border,
              focusedBorder: border,
              enabledBorder: border,
              errorBorder: border,
              contentPadding: EdgeInsets.symmetric(vertical: 8.toScreenHeight, horizontal: 16.toScreenWidth),
              constraints: const BoxConstraints(),
              suffixIconConstraints: const BoxConstraints(maxHeight: 24, maxWidth: 24 + 8),
              filled: true,
              fillColor: AppColor.dropDownBackground(context),
              errorStyle: AppTextStyle.tiny.copyWith(color: context.isDark ? AppColor.red50 : AppColor.red60),
              // floatingLabelStyle: AppTextStyle.body1.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? null : AppColor.neutral20),
              floatingLabelStyle: TextStyle(fontWeight: FontWeight.w500, fontSize: context.isTablet() ? 16 : 12, color: AppColor.floatingTextStyleColor(context)),
              labelStyle: TextStyle(fontWeight: FontWeight.w500, fontSize: context.isTablet() ? 16 : 12, color: AppColor.labelTextStyleColor(context)),
              labelText: "Users going to use technology",
              // labelStyle: AppTextStyles.tinyFont.copyWith(color: AppColor.textColor(context)),
              suffixIcon: loading ? CircularProgressIndicator(color: AppColor.loadingColor(context), strokeWidth: 3.0).paddingOnly(end: 8) : null,
            ),
            textInputAction: TextInputAction.search,
            onChanged: (text) {
              fieldTextEditingController.text = text;
            },
            onSubmitted: (String value) {
              onFieldSubmitted();
            },
          );
        },
        onSelected: (UsersBasedOnSearchModel selection) {
          if (widget.clearAfterPick) {
            _controller.clear();
          } else {
            _controller.text = widget.byName ? (selection.userName ?? "") : (selection.employeeId ?? "");
          }
          widget.onPick(selection);
        },
      ),
    );
  }
}
