
import 'package:dio/dio.dart';
import '../general/search_bar.dart';
import 'package:flutter/material.dart';

import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/located_address.dart';
import '../../pages/new_address.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/utils.dart';

class MobileSearchPlace extends StatefulWidget {
  final Key? key;
  final int businessId;
  const MobileSearchPlace(this.businessId, {this.key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MobileSearchPlaceState();
  }

}

class MobileSearchPlaceState extends State<MobileSearchPlace> {

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    return Scaffold(
      appBar: AppBar(
        leading:  IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: (){
              Navigator.of(context).pop();
            }
        ),
        title: Text(
          S.of(context).search_place,
        ),
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20.0),
          child: SearchBar(
            minimumChars: 6,
            hintText: S.of(context).enter_delivery_address,
            cancellationWidget: Text(
              S.of(context).cancel,
            ),
            onSearch: search,
            onItemFound: (LocatedAddress locatedAddress, int index) {
              return ListTile(
                title: Text(locatedAddress.streetName),
                subtitle: Text(locatedAddress.formattedAddress),
                onTap: () {
                  if (widget.businessId == 0) {
                    _selectPlace(locatedAddress);
                  } else {
                    _selectPlaceAsNew(locatedAddress);
                  }
                },
                dense: true,

              );
            },
            onError: (error) {
              return Center(
                child: Text("$error"),
              );
            },
            emptyWidget: Center(
              child: widget.businessId > 0 ?
              GestureDetector(
                child: Text(
                  S.of(context).empty_address_change_keyword,
                ),
                onTap: () {
                  _selectPlaceAsNew(null);
                },
              ) :
              Text(
                  S.of(context).empty_result_change_keyword
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  Future<List<LocatedAddress>> search(String keyword) async {
    var result = await HttpUtil.httpGet('v1/search-places',
      queryParameters: {
        'keyword': keyword,
      },
      returnError: true,
    );
    if (result is DioError) {
      if (result.response != null) {
        throw RuntimeError(result.response.data['message']);
      } else {
        throw RuntimeError(result.message);
      }
    } else if (result != null && result is List) {
      return result.map((e) => LocatedAddress.fromJson(e)).toList();
    }
    return [];
  }

  void _selectPlace(LocatedAddress locatedAddress) {
    store.dispatch(UpdateLocatedAddress(locatedAddress));
    eventBus.fire(OnUpdateLocatedAddressSuccess());
    Navigator.of(context).pop();
  }

  void _selectPlaceAsNew(LocatedAddress locatedAddress) {
    print('located address: ${locatedAddress.toString()}');
    Navigator.push(context, MaterialPageRoute(
      builder: (BuildContext context) => NewAddress(locatedAddress: locatedAddress, businessId: widget.businessId,),
    ));
  }
}