import React, { useEffect, useRef, useState } from 'react';
import { Box } from '@chakra-ui/react';
import maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';

interface VectorMapProps {
  latitude: number;
  longitude: number;
  zoom?: number;
  address?: string;
  clubName?: string;
  mapStyle?: 'positron' | 'dark-matter' | 'osm-bright' | 'klokantech-basic';
  height?: number;
  clubPrimaryColor?: string;
  clubSecondaryColor?: string;
  customStyleUrl?: string;
}

// OpenMapTiles free demo server (for development/testing)
// For production, use your own tile server or a commercial provider
const MAPTILER_API_KEY = process.env.REACT_APP_MAPTILER_KEY || 'get_your_own_OpIi9ZULNHzrESv6T2vL';

// Vector tile style definitions
export const VECTOR_STYLES = {
  'positron': {
    name: 'Positron (Light)',
    description: 'Clean light style, perfect for data visualization',
    getStyleUrl: (apiKey: string) => `https://api.maptiler.com/maps/positron/style.json?key=${apiKey}`,
  },
  'dark-matter': {
    name: 'Dark Matter',
    description: 'Sleek dark theme for modern interfaces',
    getStyleUrl: (apiKey: string) => `https://api.maptiler.com/maps/darkmatter/style.json?key=${apiKey}`,
  },
  'osm-bright': {
    name: 'OSM Bright',
    description: 'Colorful OpenStreetMap style',
    getStyleUrl: (apiKey: string) => `https://api.maptiler.com/maps/bright/style.json?key=${apiKey}`,
  },
  'klokantech-basic': {
    name: 'Basic',
    description: 'Simple and clean base map',
    getStyleUrl: (apiKey: string) => `https://api.maptiler.com/maps/basic/style.json?key=${apiKey}`,
  },
};

// Custom Positron-like style with club colors (self-hosted tiles not required)
const createCustomPositronStyle = (primaryColor?: string, secondaryColor?: string): any => {
  const mainColor = primaryColor || '#e11d48';
  const accentColor = secondaryColor || '#3b82f6';
  
  return {
    version: 8,
    name: 'Custom Positron',
    sources: {
      'openmaptiles': {
        type: 'vector',
        url: `https://api.maptiler.com/tiles/v3/tiles.json?key=${MAPTILER_API_KEY}`,
      },
    },
    glyphs: 'https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key=' + MAPTILER_API_KEY,
    layers: [
      // Background
      {
        id: 'background',
        type: 'background',
        paint: { 'background-color': '#f8f8f8' },
      },
      // Water
      {
        id: 'water',
        type: 'fill',
        source: 'openmaptiles',
        'source-layer': 'water',
        paint: { 'fill-color': '#e3e8ed' },
      },
      // Parks
      {
        id: 'park',
        type: 'fill',
        source: 'openmaptiles',
        'source-layer': 'park',
        paint: { 'fill-color': '#e8f5e8' },
      },
      // Buildings
      {
        id: 'building',
        type: 'fill',
        source: 'openmaptiles',
        'source-layer': 'building',
        paint: {
          'fill-color': '#ececec',
          'fill-opacity': 0.6,
        },
      },
      // Roads - major
      {
        id: 'road-major',
        type: 'line',
        source: 'openmaptiles',
        'source-layer': 'transportation',
        filter: ['in', 'class', 'motorway', 'trunk', 'primary'],
        paint: {
          'line-color': '#ffffff',
          'line-width': {
            base: 1.4,
            stops: [[6, 0.5], [20, 30]],
          },
        },
      },
      // Roads - minor
      {
        id: 'road-minor',
        type: 'line',
        source: 'openmaptiles',
        'source-layer': 'transportation',
        filter: ['in', 'class', 'secondary', 'tertiary', 'minor'],
        paint: {
          'line-color': '#ffffff',
          'line-width': {
            base: 1.4,
            stops: [[6, 0.25], [20, 20]],
          },
        },
      },
      // Place labels
      {
        id: 'place-label',
        type: 'symbol',
        source: 'openmaptiles',
        'source-layer': 'place',
        layout: {
          'text-field': '{name}',
          'text-font': ['Noto Sans Regular'],
          'text-size': {
            base: 1.2,
            stops: [[7, 11], [15, 14]],
          },
        },
        paint: {
          'text-color': '#666666',
          'text-halo-color': '#ffffff',
          'text-halo-width': 1.5,
        },
      },
    ],
  };
};

const VectorMap: React.FC<VectorMapProps> = ({
  latitude,
  longitude,
  zoom = 15,
  address,
  clubName,
  mapStyle = 'positron',
  height = 400,
  clubPrimaryColor,
  clubSecondaryColor,
  customStyleUrl,
}) => {
  const mapContainer = useRef<HTMLDivElement>(null);
  const map = useRef<maplibregl.Map | null>(null);
  const marker = useRef<maplibregl.Marker | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!mapContainer.current || map.current) return;

    try {
      // Determine style URL
      let styleUrl: string | any;
      
      if (customStyleUrl) {
        styleUrl = customStyleUrl;
      } else if (mapStyle === 'positron' && clubPrimaryColor) {
        // Use custom style with club colors
        styleUrl = createCustomPositronStyle(clubPrimaryColor, clubSecondaryColor);
      } else {
        // Use predefined style
        styleUrl = VECTOR_STYLES[mapStyle]?.getStyleUrl(MAPTILER_API_KEY) || 
                   VECTOR_STYLES.positron.getStyleUrl(MAPTILER_API_KEY);
      }

      // Initialize map
      map.current = new maplibregl.Map({
        container: mapContainer.current,
        style: styleUrl,
        center: [longitude, latitude],
        zoom: zoom,
      });

      // Add navigation controls
      map.current.addControl(new maplibregl.NavigationControl(), 'top-right');

      // Create custom marker with club color
      const markerColor = clubPrimaryColor || '#e11d48';
      
      // Create marker element
      const el = document.createElement('div');
      el.style.width = '36px';
      el.style.height = '54px';
      el.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 36" width="36" height="54">
          <defs>
            <filter id="marker-shadow-${Date.now()}" x="-50%" y="-50%" width="200%" height="200%">
              <feGaussianBlur in="SourceAlpha" stdDeviation="2"/>
              <feOffset dx="0" dy="2" result="offsetblur"/>
              <feComponentTransfer>
                <feFuncA type="linear" slope="0.3"/>
              </feComponentTransfer>
              <feMerge>
                <feMergeNode/>
                <feMergeNode in="SourceGraphic"/>
              </feMerge>
            </filter>
          </defs>
          <path fill="${markerColor}" stroke="#fff" stroke-width="1.5" 
                filter="url(#marker-shadow-${Date.now()})"
                d="M12 0C7.03 0 3 4.03 3 9c0 7.5 9 18 9 18s9-10.5 9-18c0-4.97-4.03-9-9-9z"/>
          <circle cx="12" cy="9" r="3" fill="#fff"/>
        </svg>
      `;

      // Add marker to map
      marker.current = new maplibregl.Marker({ element: el })
        .setLngLat([longitude, latitude])
        .addTo(map.current);

      // Add popup if there's content
      if (clubName || address) {
        let popupContent = '';
        if (clubName) popupContent += `<strong>${clubName}</strong><br>`;
        if (address) popupContent += address;
        
        const popup = new maplibregl.Popup({ offset: 25 })
          .setHTML(popupContent);
        
        marker.current.setPopup(popup);
      }

      // Handle map load event for additional customization
      map.current.on('load', () => {
        if (!map.current) return;
        
        // Apply club color tint to water features if primary color is set
        if (clubPrimaryColor && map.current.getLayer('water')) {
          map.current.setPaintProperty('water', 'fill-color', 
            adjustColorBrightness(clubPrimaryColor, 0.9));
        }
      });

    } catch (err: any) {
      console.error('Error initializing map:', err);
      setError(err?.message || 'Failed to load map');
    }

    // Cleanup
    return () => {
      if (marker.current) {
        marker.current.remove();
        marker.current = null;
      }
      if (map.current) {
        map.current.remove();
        map.current = null;
      }
    };
  }, [latitude, longitude, zoom, mapStyle, clubPrimaryColor, clubSecondaryColor, customStyleUrl]);

  // Update marker and center when coordinates change
  useEffect(() => {
    if (!map.current || !marker.current) return;
    
    const newCenter: [number, number] = [longitude, latitude];
    marker.current.setLngLat(newCenter);
    map.current.setCenter(newCenter);
  }, [latitude, longitude]);

  // Helper function to adjust color brightness
  function adjustColorBrightness(color: string, factor: number): string {
    try {
      // Simple RGB adjustment
      const hex = color.replace('#', '');
      const r = Math.min(255, Math.floor(parseInt(hex.substring(0, 2), 16) * factor));
      const g = Math.min(255, Math.floor(parseInt(hex.substring(2, 4), 16) * factor));
      const b = Math.min(255, Math.floor(parseInt(hex.substring(4, 6), 16) * factor));
      return `rgb(${r}, ${g}, ${b})`;
    } catch {
      return color;
    }
  }

  if (error) {
    return (
      <Box
        w="100%"
        h={`${height}px`}
        bg="gray.100"
        display="flex"
        alignItems="center"
        justifyContent="center"
        borderRadius="md"
        p={4}
      >
        {error}
      </Box>
    );
  }

  return (
    <Box
      ref={mapContainer}
      w="100%"
      h={`${height}px`}
      borderRadius="md"
      overflow="hidden"
      boxShadow="md"
    />
  );
};

export default VectorMap;
