import 'package:flutter_map/flutter_map.dart';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
import 'package:lba/utils/theme_manager.dart';

class MapTileProviders {
  static const List<Map<String, dynamic>> _tileProviders = [
    {
      'name': 'Stamen Terrain',
      'lightUrl': 'https://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}{r}.png',
      'darkUrl': 'https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}{r}.png',
      'subdomains': ['a', 'b', 'c', 'd'],
    },
    {
      'name': 'CartoDB',
      'lightUrl': 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',
      'darkUrl': 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',
      'subdomains': ['a', 'b', 'c', 'd'],
    },
    {
      'name': 'Google Maps',
      'lightUrl': 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
      'darkUrl': 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}',
      'subdomains': ['mt0', 'mt1', 'mt2', 'mt3'],
    },
  ];

  static List<Map<String, dynamic>> get providers => _tileProviders;

  static TileLayer createTileLayer({
    required BuildContext context,
    int currentProvider = 0,
    Function(int)? onProviderChange,
    void Function(Object, dynamic, dynamic)? errorCallback,
  }) {
    final themeManager = Provider.of<ThemeManager>(context, listen: false);
    final isDarkMode = themeManager.isDarkMode;
    final safeProviderIndex = currentProvider.clamp(0, _tileProviders.length - 1);
    
    return TileLayer(
      urlTemplate: isDarkMode 
          ? _tileProviders[safeProviderIndex]['darkUrl']
          : _tileProviders[safeProviderIndex]['lightUrl'],
      userAgentPackageName: 'com.example.lba',
      subdomains: _tileProviders[safeProviderIndex]['subdomains'],
      additionalOptions: const {
        'attribution': '© Map contributors',
      },
      errorTileCallback: errorCallback ?? _defaultErrorCallback(onProviderChange),
    );
  }

  static void Function(Object, dynamic, dynamic) _defaultErrorCallback(Function(int)? onProviderChange) {
    bool _isSwitching = false;
    
    return (tile, error, stackTrace) {
      if (!_isSwitching && onProviderChange != null) {
        _isSwitching = true;
        
        Future.delayed(const Duration(milliseconds: 500), () {
          onProviderChange(1);
          _isSwitching = false;
        });
      }
    };
  }

  static String getProviderName(int index) {
    final safeIndex = index.clamp(0, _tileProviders.length - 1);
    return _tileProviders[safeIndex]['name'];
  }

  static int get providerCount => _tileProviders.length;
}
