import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.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, this.byName, this.initialValue, this.assetId, this.onPick, this.clearAfterPick = true}) : super(key: key);

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

class _AutoCompletePartsFieldState extends State<AutoCompletePartsField> {
  SettingProvider _settingProvider;
  PartsProvider _partsProvider;
  UserProvider _userProvider;
  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(10));

    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: TypeAheadField<SparePartsWorkOrders>(
        minCharsForSuggestions: 1,
        textFieldConfiguration: TextFieldConfiguration(
          style: AppTextStyles.bodyText,
          controller: _controller,
          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: (context.isDark ? AppColor.neutral50 : AppColor.background(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,
          ),
          textInputAction: TextInputAction.search,
        ),
        suggestionsCallback: (value) async {
          return (await _partsProvider.getPartsList(partName: widget.byName ? value : null, partNo: widget.byName ? null : value, assetId: widget.assetId))
              .map((e) => SparePartsWorkOrders(sparePart: e))
              .toList();
        },
        itemBuilder: (context, part) {
          return ListTile(
            title: Text(part?.sparePart?.partNo ?? ""),
            subtitle: Text(
              part?.sparePart?.partName ?? "",
              style: Theme.of(context).textTheme.bodySmall,
            ),
          );
        },
        onSuggestionSelected: (part) {
          if (widget.clearAfterPick) {
            _controller.clear();
          } else {
            _controller.text = widget.byName ? (part?.sparePart?.partName ?? "") : (part?.sparePart?.partNo ?? "");
          }
          widget.onPick(part);
        },
      ),
    );
  }
}
