import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:google_places_flutter/google_places_flutter.dart';
import 'package:google_places_flutter/model/prediction.dart';
import 'package:krow_core/core.dart';

import '../../util/hubs_constants.dart';

class HubAddressAutocomplete extends StatelessWidget {
  const HubAddressAutocomplete({
    required this.controller,
    required this.hintText,
    this.focusNode,
    this.onSelected,
    super.key,
  });

  final TextEditingController controller;
  final String hintText;
  final FocusNode? focusNode;
  final void Function(Prediction prediction)? onSelected;

  @override
  Widget build(BuildContext context) {
    return GooglePlaceAutoCompleteTextField(
      textEditingController: controller,
      focusNode: focusNode,
      googleAPIKey: AppConfig.googleMapsApiKey,
      debounceTime: 500,
      countries: HubsConstants.supportedCountries,
      isLatLngRequired: true,
      getPlaceDetailWithLatLng: (Prediction prediction) {
        onSelected?.call(prediction);
      },
      itemClick: (Prediction prediction) {
        controller.text = prediction.description ?? '';
        controller.selection = TextSelection.fromPosition(
          TextPosition(offset: controller.text.length),
        );
        onSelected?.call(prediction);
      },
      itemBuilder: (BuildContext context, int index, Prediction prediction) {
        return Padding(
          padding: const EdgeInsets.all(UiConstants.space2),
          child: Row(
            spacing: UiConstants.space1,
            children: <Widget>[
              const Icon(UiIcons.mapPin, color: UiColors.iconSecondary),
              Expanded(
                child: Text(
                  prediction.description ?? "",
                  style: UiTypography.body1r.textSecondary,
                ),
              ),
            ],
          ),
        );
      },
      textStyle: UiTypography.body1r.textPrimary,
    );
  }
}
