#import "FGGoogleMaps.h"
#import "FGStore.h"

static NSString *const kPlacesHost = @"https://places.googleapis.com/v1";
static NSString *const kGeocodeHost = @"https://maps.googleapis.com/maps/api/geocode/json";

@implementation FGGoogleMaps

+ (BOOL)isConfigured {
    NSString *key = [FGStore googleAPIKey];
    return key.length > 10;
}

+ (void)openAPIKeyPage {
    NSURL *url = [NSURL URLWithString:@"https://console.cloud.google.com/google/maps-apis/credentials"];
    if (url) [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
}

#pragma mark - Mạng

+ (void)JSONRequest:(NSURLRequest *)request
         completion:(void (^)(id json, NSString *errorMessage))completion {
    NSURLSessionDataTask *task = [[NSURLSession sharedSession]
        dataTaskWithRequest:request
          completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
              if (error) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                      completion(nil, @"Không kết nối được máy chủ. Kiểm tra mạng rồi thử lại.");
                  });
                  return;
              }

              NSInteger status = [(NSHTTPURLResponse *)response statusCode];
              id json = nil;
              if (data.length) {
                  json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
              }

              if (status < 200 || status >= 300) {
                  NSString *detail = nil;
                  if ([json isKindOfClass:[NSDictionary class]]) {
                      detail = json[@"error"][@"message"];
                  }
                  NSString *message = detail.length
                      ? [NSString stringWithFormat:@"Google API báo lỗi (%ld): %@", (long)status, detail]
                      : [NSString stringWithFormat:@"Google API báo lỗi (HTTP %ld).", (long)status];
                  dispatch_async(dispatch_get_main_queue(), ^{
                      completion(nil, message);
                  });
                  return;
              }

              dispatch_async(dispatch_get_main_queue(), ^{
                  completion(json, nil);
              });
          }];
    [task resume];
}

+ (NSMutableURLRequest *)requestWithURL:(NSURL *)url
                                 method:(NSString *)method
                                   body:(NSDictionary *)body {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = method;
    request.timeoutInterval = 15.0;
    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    if (body) {
        request.HTTPBody = [NSJSONSerialization dataWithJSONObject:body options:0 error:NULL];
    }
    return request;
}

#pragma mark - Autocomplete

+ (void)autocompleteQuery:(NSString *)query
               completion:(void (^)(NSArray<NSDictionary *> *, NSString *))completion {
    if (![self isConfigured]) {
        completion(@[], @"Chưa cấu hình Google API key.");
        return;
    }
    if (query.length < 2) {
        completion(@[], nil);
        return;
    }

    NSURL *url = [NSURL URLWithString:[kPlacesHost stringByAppendingString:@"/places:autocomplete"]];
    NSMutableURLRequest *request = [self requestWithURL:url method:@"POST" body:@{ @"input": query, @"languageCode": @"vi" }];
    [request setValue:[FGStore googleAPIKey] forHTTPHeaderField:@"X-Goog-Api-Key"];
    [request setValue:@"suggestions.placePrediction.placeId,suggestions.placePrediction.text.text,suggestions.placePrediction.structuredFormat.mainText.text,suggestions.placePrediction.structuredFormat.secondaryText.text"
   forHTTPHeaderField:@"X-Goog-FieldMask"];

    [self JSONRequest:request completion:^(id json, NSString *errorMessage) {
        if (errorMessage) {
            completion(@[], errorMessage);
            return;
        }

        NSMutableArray *results = [NSMutableArray array];
        NSArray *suggestions = [json isKindOfClass:[NSDictionary class]] ? json[@"suggestions"] : nil;
        for (NSDictionary *entry in suggestions) {
            NSDictionary *prediction = entry[@"placePrediction"];
            if (![prediction isKindOfClass:[NSDictionary class]]) continue;

            NSString *placeID = prediction[@"placeId"];
            NSString *title = prediction[@"structuredFormat"][@"mainText"][@"text"]
                              ?: prediction[@"text"][@"text"];
            NSString *subtitle = prediction[@"structuredFormat"][@"secondaryText"][@"text"];
            if (!placeID.length || !title.length) continue;

            [results addObject:@{
                @"title": title,
                @"subtitle": subtitle ?: @"",
                @"placeID": placeID
            }];
        }
        completion(results, nil);
    }];
}

#pragma mark - Chi tiết địa điểm

+ (void)lookupPlaceID:(NSString *)placeID
           completion:(void (^)(NSDictionary *, NSString *))completion {
    if (![self isConfigured]) {
        completion(nil, @"Chưa cấu hình Google API key.");
        return;
    }

    NSString *encoded = [placeID stringByAddingPercentEncodingWithAllowedCharacters:
                         [NSCharacterSet URLPathAllowedCharacterSet]];
    NSString *path = [NSString stringWithFormat:@"/places/%@?languageCode=vi&fields=displayName,formattedAddress,location", encoded];
    NSURL *url = [NSURL URLWithString:[kPlacesHost stringByAppendingString:path]];

    NSMutableURLRequest *request = [self requestWithURL:url method:@"GET" body:nil];
    [request setValue:[FGStore googleAPIKey] forHTTPHeaderField:@"X-Goog-Api-Key"];
    [self JSONRequest:request completion:^(id json, NSString *errorMessage) {
        if (errorMessage) {
            completion(nil, errorMessage);
            return;
        }

        NSDictionary *location = json[@"location"];
        double lat = [location[@"latitude"] doubleValue];
        double lng = [location[@"longitude"] doubleValue];
        NSString *name = json[@"displayName"][@"text"] ?: @"";
        NSString *address = json[@"formattedAddress"] ?: name;

        if (!FGCoordinateValid(FGCoordinateMake(lat, lng))) {
            completion(nil, @"Không lấy được toạ độ của địa điểm.");
            return;
        }

        completion(@{
            @"name": name,
            @"address": address,
            @"lat": @(lat),
            @"lng": @(lng)
        }, nil);
    }];
}

#pragma mark - Tìm kiếm văn bản

+ (void)searchQuery:(NSString *)query
         completion:(void (^)(NSDictionary *, NSString *))completion {
    if (![self isConfigured]) {
        [self appleSearchQuery:query completion:completion];
        return;
    }

    NSURL *url = [NSURL URLWithString:[kPlacesHost stringByAppendingString:@"/places:searchText"]];
    NSMutableURLRequest *request = [self requestWithURL:url method:@"POST"
                                                  body:@{ @"textQuery": query, @"languageCode": @"vi" }];
    [request setValue:[FGStore googleAPIKey] forHTTPHeaderField:@"X-Goog-Api-Key"];
    [request setValue:@"places.id,places.displayName,places.formattedAddress,places.location"
   forHTTPHeaderField:@"X-Goog-FieldMask"];

    [self JSONRequest:request completion:^(id json, NSString *errorMessage) {
        if (errorMessage) {
            completion(nil, errorMessage);
            return;
        }

        NSArray *places = [json isKindOfClass:[NSDictionary class]] ? json[@"places"] : nil;
        NSDictionary *first = places.firstObject;
        if (![first isKindOfClass:[NSDictionary class]]) {
            completion(nil, @"Không tìm thấy địa điểm phù hợp.");
            return;
        }

        NSDictionary *location = first[@"location"];
        double lat = [location[@"latitude"] doubleValue];
        double lng = [location[@"longitude"] doubleValue];
        NSString *name = first[@"displayName"][@"text"] ?: @"";
        NSString *address = first[@"formattedAddress"] ?: name;

        if (!FGCoordinateValid(FGCoordinateMake(lat, lng))) {
            completion(nil, @"Không lấy được toạ độ của địa điểm.");
            return;
        }

        completion(@{
            @"name": name,
            @"address": address,
            @"lat": @(lat),
            @"lng": @(lng)
        }, nil);
    }];
}

+ (void)appleSearchQuery:(NSString *)query
              completion:(void (^)(NSDictionary *, NSString *))completion {
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
    request.naturalLanguageQuery = query;
    MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:request];
    [search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            MKMapItem *item = response.mapItems.firstObject;
            if (!item) {
                completion(nil, error.localizedDescription ?: @"Không tìm thấy địa điểm phù hợp.");
                return;
            }
            CLLocationCoordinate2D coordinate = item.placemark.coordinate;
            NSString *name = item.name ?: item.placemark.name ?: @"";
            NSString *address = item.placemark.title ?: name;
            completion(@{
                @"name": name,
                @"address": address,
                @"lat": @(coordinate.latitude),
                @"lng": @(coordinate.longitude)
            }, nil);
        });
    }];
}

#pragma mark - Dịch ngược toạ độ

+ (void)reverseGeocode:(CLLocationCoordinate2D)coordinate
            completion:(void (^)(NSString *))completion {
    if (![self isConfigured]) {
        [self appleReverseGeocode:coordinate completion:completion];
        return;
    }

    NSString *latlng = [NSString stringWithFormat:@"%.6f,%.6f", coordinate.latitude, coordinate.longitude];
    NSURLComponents *components = [NSURLComponents componentsWithString:kGeocodeHost];
    components.queryItems = @[
        [NSURLQueryItem queryItemWithName:@"latlng" value:latlng],
        [NSURLQueryItem queryItemWithName:@"language" value:@"vi"],
        [NSURLQueryItem queryItemWithName:@"key" value:[FGStore googleAPIKey]]
    ];

    NSMutableURLRequest *request = [self requestWithURL:components.URL method:@"GET" body:nil];

    [self JSONRequest:request completion:^(id json, NSString *errorMessage) {
        NSArray *results = [json isKindOfClass:[NSDictionary class]] ? json[@"results"] : nil;
        NSString *address = [results.firstObject isKindOfClass:[NSDictionary class]]
            ? results.firstObject[@"formatted_address"] : nil;
        if (address.length) {
            completion(address);
        } else {
            [self appleReverseGeocode:coordinate completion:completion];
        }
    }];
}

+ (void)appleReverseGeocode:(CLLocationCoordinate2D)coordinate
                 completion:(void (^)(NSString *))completion {
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude
                                                      longitude:coordinate.longitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> *placemarks, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            CLPlacemark *placemark = placemarks.firstObject;
            if (!placemark) {
                completion(@"");
                return;
            }

            NSMutableArray *parts = [NSMutableArray array];
            void (^add)(NSString *) = ^(NSString *value) {
                if (value.length && ![parts containsObject:value]) [parts addObject:value];
            };
            add(placemark.name);
            add(placemark.subLocality);
            add(placemark.locality);
            add(placemark.administrativeArea);
            add(placemark.country);

            completion([parts componentsJoinedByString:@", "]);
        });
    }];
}

@end
