import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/parts_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/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 AutoCompletePartsField extends StatefulWidget {
  final String initialValue;
  final num? assetId;
  final bool clearAfterPick, byName;
  final Function(SparePartsWorkOrders) onPick;

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

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

class _AutoCompletePartsFieldState extends State<AutoCompletePartsField> {
  late SettingProvider _settingProvider;
  late PartsProvider _partsProvider;
  late UserProvider _userProvider;
  late TextEditingController _controller;

  @override
  void initState() {
    _controller = TextEditingController(text: widget.initialValue);
    super.initState();
  }

  @override
  void didUpdateWidget(covariant AutoCompletePartsField 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) {
    _settingProvider = Provider.of<SettingProvider>(context);
    _userProvider = Provider.of<UserProvider>(context);
    _partsProvider = Provider.of<PartsProvider>(context);
    final border = UnderlineInputBorder(borderSide: BorderSide.none, borderRadius: BorderRadius.circular(16));
    return Container(
      decoration: BoxDecoration(
        color: AppColor.background(context),
        borderRadius: BorderRadius.circular(AppStyle.borderRadius * AppStyle.getScaleFactor(context)),
        //  boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
      ),
      child: Autocomplete<SparePartsWorkOrders>(
        optionsBuilder: (TextEditingValue textEditingValue) async {
          if (textEditingValue.text.isEmpty) {
            return const Iterable<SparePartsWorkOrders>.empty();
          }
          return (await _partsProvider.getPartsList(partName: widget.byName ? textEditingValue.text : null, partNo: widget.byName ? null : textEditingValue.text, assetId: widget.assetId))
              .map((e) => SparePartsWorkOrders(sparePart: e))
              .toList();
        },
        displayStringForOption: (SparePartsWorkOrders option) => widget.byName ? option.sparePart?.partName ?? "" : option.sparePart?.partNo ?? "",
        fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) {
          return TextField(
            controller: _controller,
            focusNode: fieldFocusNode,
            style: AppTextStyles.bodyText.copyWith(color: AppColor.black10),
            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(minWidth: 0),
              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),
              labelText: widget.byName ? context.translation.partName : context.translation.partNumber,
              labelStyle: AppTextStyles.tinyFont.copyWith(color: AppColor.textColor(context)),
            ),
            textInputAction: TextInputAction.search,
            onChanged: (text) {
              fieldTextEditingController.text = text;
            },
            onSubmitted: (String value) {
              onFieldSubmitted();
            },
          );
        },
        onSelected: (SparePartsWorkOrders selection) {
          if (widget.clearAfterPick) {
            _controller.clear();
          } else {
            _controller.text = widget.byName ? (selection.sparePart?.partName ?? "") : (selection.sparePart?.partNo ?? "");
          }
          widget.onPick(selection);
        },
      ),
    );
  }
}
