import * as FileSystem from 'expo-file-system';
import MapLibreGL from '@maplibre/maplibre-react-native';

import { VECTOR_MAP_HOST } from 'src/constants';

const baseTilesDir = `${FileSystem.cacheDirectory}tiles/`;
const STYLE_URL = `${VECTOR_MAP_HOST}/nomadmania-maps.json`;
const PACK_NAME = 'vector-map-pack';

async function deleteCachedTilesIfExist(): Promise<void> {
  try {
    const dirInfo = await FileSystem.getInfoAsync(baseTilesDir, { size: true });
    if (dirInfo.exists) {
      await FileSystem.deleteAsync(baseTilesDir, { idempotent: true });
    }
  } catch (error) {
    console.error('Error deleting cached tiles:', error);
  }
}

async function setupOfflineRegion(): Promise<void> {
  try {
    const bounds: [GeoJSON.Position, GeoJSON.Position] = [
      [-180, -85],
      [180, 85]
    ];
    const minZoom = 0;
    const maxZoom = 6;

    const existingPacks = await MapLibreGL.offlineManager.getPacks();
    const pack = existingPacks.find((pack) => pack.name === PACK_NAME);

    if (pack) {
      const status = await pack.status();
      if (status.percentage < 100) {
        pack.resume();
      }
    } else {
      await MapLibreGL.offlineManager.createPack(
        {
          name: PACK_NAME,
          bounds,
          minZoom,
          maxZoom,
          styleURL: STYLE_URL
        },
        (offlineRegion, status) => {},
        (error) => {
          if (error) {
            console.error('Error creating offline pack:', error);
          }
        }
      );
    }
  } catch (error) {
    console.error('Error setting up offline pack:', error);
  }
}

export async function initOfflineSetup(): Promise<void> {
  await deleteCachedTilesIfExist();
  await setupOfflineRegion();
}
