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/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/wo_by_asset_id_model.dart';
import 'package:test_sa/modules/cm_module/cm_detail_provider.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 WoAutoCompleteField extends StatefulWidget {
  final String initialValue;
  final int? assetId;
  final bool clearAfterPick, byName, enabled;
  final Function(WoByAssetIdModel) onPick;

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

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

class _WoAutoCompleteFieldState extends State<WoAutoCompleteField> {
  late CMDetailProvider _cmDetailProvider;

  late TextEditingController _controller;

  bool loading = false;

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

  @override
  void didUpdateWidget(covariant WoAutoCompleteField 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),
        border: Border.all(color: AppColor.border2Color(context), width: 1),
        borderRadius: BorderRadius.circular(16),
        //  boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
      ),
      child: Autocomplete<WoByAssetIdModel>(
        optionsBuilder: (TextEditingValue textEditingValue) async {
          if (textEditingValue.text.isEmpty) {
            if (loading) {
              setState(() {
                loading = false;
              });
            }
            return const Iterable<WoByAssetIdModel>.empty();
          }
          if (!loading) {
            setState(() {
              loading = true;
            });
          }
          List<WoByAssetIdModel> workOrders = (await _cmDetailProvider.getWorkOrderByAssetId(textEditingValue.text, widget.assetId!));

          setState(() {
            loading = false;
          });
          return workOrders;
        },
        displayStringForOption: (WoByAssetIdModel option) => widget.byName ? option.workOrderNo ?? "" : option.workOrderNo ?? "",
        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)),
            textAlign: TextAlign.start,
            decoration: InputDecoration(
              border: border,
              disabledBorder: border,
              focusedBorder: border,
              enabledBorder: border,
              errorBorder: border,
              contentPadding: EdgeInsets.symmetric(vertical: 12.toScreenHeight, horizontal: 16.toScreenWidth),
              constraints: const BoxConstraints(),
              suffixIconConstraints: const BoxConstraints(maxHeight: 24, maxWidth: 24 + 8),
              filled: true,
              enabled: widget.enabled,
              fillColor: AppColor.dropDownBackground(context),
              errorStyle: AppTextStyle.tiny.copyWith(color: context.isDark ? AppColor.red50 : AppColor.red60),
              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: "CM Work Order Number",
              suffixIcon: loading ? const CircularProgressIndicator(color: AppColor.primary10, strokeWidth: 3.0).paddingOnly(end: 8) : null,
            ),
            textInputAction: TextInputAction.search,
            onChanged: (text) {
              fieldTextEditingController.text = text;
            },
            onSubmitted: (String value) {
              onFieldSubmitted();
            },
          );
        },
        onSelected: (WoByAssetIdModel selection) {
          if (widget.clearAfterPick) {
            _controller.clear();
          } else {
            _controller.text = widget.byName ? (selection.workOrderNo ?? "") : (selection.workOrderNo ?? "");
          }
          widget.onPick(selection);
        },
      ),
    );
  }
}
