import 'dart:convert';
import 'dart:math';

import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class ZonesController extends GetxController {
  Map<String, List<LatLng>> generateZoneMap(
      LatLng southwest, LatLng southEast, LatLng northeast) {
    const double desiredZoneArea = 4; // in square kilometers

    final double width = (southEast.longitude - southwest.longitude) * 100;
    final double height = (northeast.latitude - southEast.latitude) * 100;
    final double totalArea = width * height;
    print(width);
    print(height);

    // final int numZones = (totalArea / desiredZoneArea).ceil();

    final double zoneWidth = width / sqrt(desiredZoneArea);
    final double zoneHeight = height / sqrt(desiredZoneArea);
    final numRows =
        ((northeast.latitude - southwest.latitude) / zoneHeight).ceil();
    final numCols =
        ((southEast.longitude - southwest.longitude) / zoneWidth).ceil();
    print('zoneWidth = $zoneWidth');
    print('zoneHeight = $zoneHeight');
    List<String> zoneNames = [];
    List<LatLng> zoneCoordinates = [];

    for (int row = 0; row < numRows; row++) {
      for (int col = 0; col < numCols; col++) {
        final double zoneSouthwestLat =
            southwest.latitude + (row * zoneHeight / 100);
        final double zoneSouthwestLng =
            southwest.longitude + (col * zoneWidth / 100);
        final double zoneNortheastLat = zoneSouthwestLat + zoneHeight / 100;
        final double zoneNortheastLng = zoneSouthwestLng + zoneWidth / 100;

        LatLng zoneSouthwest = LatLng(zoneSouthwestLat, zoneSouthwestLng);
        LatLng zoneNortheast = LatLng(zoneNortheastLat, zoneNortheastLng);

        String zoneName =
            'Zone${row + col}'; // Assign a unique name to each zone

        zoneNames.add(zoneName);
        zoneCoordinates.add(zoneSouthwest);
        zoneCoordinates.add(zoneNortheast);
      }
    }

    Map<String, List<LatLng>> zoneMap = {};
    for (int i = 0; i < zoneNames.length; i++) {
      zoneMap[zoneNames[i]] = [
        zoneCoordinates[i], // Southwest LatLng
        zoneCoordinates[i + 1], // Northeast LatLng
      ];
    }

    return zoneMap;
  }

  void getJsonOfZones() {
    LatLng southwest = const LatLng(32.111107, 36.062222);
    LatLng southEast = const LatLng(32.108333, 36.101667);
    LatLng northeast = const LatLng(32.143889, 36.058889);
    Map<String, List<LatLng>> zoneMap =
        generateZoneMap(southwest, southEast, northeast);
    String jsonMap = json.encode(zoneMap);

    print(jsonMap);
  }
}
