import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:provider/provider.dart';

import '../../../api/login_api_client.dart';
import '../../../controllers/providers/api/parts_provider.dart';
import '../../../controllers/providers/settings/setting_provider.dart';
import '../../../controllers/providers/user_provider.dart';
import '../../../models/part.dart';
import '../../../models/user.dart';
import '../../app_style/colors.dart';
import '../../app_style/sizing.dart';
import '../loaders/loading_manager.dart';

class AutoCompletePartsField extends StatefulWidget {
  final String? initialValue;
  final Function(Part)? onPick;
  final bool? clearAfterPick;

  const AutoCompletePartsField({Key? key, this.initialValue, 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 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);
    //Subtitle _subtitle = AppLocalization.of(context).subtitle;
    return LoadingManager(
      isLoading: _partsProvider.isLoading,
      isFailedLoading: _partsProvider.parts == null,
      stateCode: _partsProvider.stateCode,
      onRefresh: () async {
        _partsProvider.reset();
        await _partsProvider.getParts(
          host: _settingProvider.host ?? "",
          user: UserApiClient().user ?? User(),
          title: '',
        );
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: AColors.black),
            borderRadius: BorderRadius.circular(AppStyle.borderRadius * AppStyle.getScaleFactor(context)),
            boxShadow: const [AppStyle.boxShadow]),
        child: TypeAheadField<Part>(
          textFieldConfiguration: TextFieldConfiguration(
            style: Theme.of(context).textTheme.subtitle1,
            controller: _controller,
            textAlign: TextAlign.center,
            decoration: const InputDecoration(
              border: InputBorder.none,
              disabledBorder: InputBorder.none,
              focusedBorder: InputBorder.none,
              enabledBorder: InputBorder.none,
            ),
            textInputAction: TextInputAction.search,
          ),
          suggestionsCallback: (vale) async {
            return await _partsProvider.getPartsList(host: _settingProvider.host ?? "", title: vale, user: User());
          },
          itemBuilder: (context, part) {
            return ListTile(
              title: Text(part.code ?? ""),
              subtitle: Text(
                part.name ?? "",
                style: Theme.of(context).textTheme.caption,
              ),
            );
          },
          onSuggestionSelected: (part) {
            if (widget.clearAfterPick ?? false) {
              _controller.clear();
            } else {
              _controller.text = part.code ?? "";
            }
            widget.onPick!(part);
          },
        ),
      ),
    );
  }
}
