import React, { useEffect, useRef, useState } from 'react';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import { createClient } from '@/lib/supabase/client';

interface GameStep {
  step: number;
  step_type: -1 | 0 | 1 | 3 | 11;  // Explicitly define the possible values
  start_lat: number;
  start_lng: number;
  end_lat: number;
  end_lng: number;
}

interface GameStepsMapProps {
  gameId: string;
}

mapboxgl.accessToken = process.env.NEXT_PUBLIC_MAPBOX_TOKEN || '';

const GameStepsMap: React.FC<GameStepsMapProps> = ({ gameId }) => {
  const mapContainer = useRef<HTMLDivElement>(null);
  const mapRef = useRef<mapboxgl.Map | null>(null);
  const [steps, setSteps] = useState<GameStep[]>([]);
  const supabase = createClient();

  // Color mapping for different step types
  const stepTypeColors = {
    '-1': '#4CAF50', // Walking - Green
    '0': '#FFC107',  // Tram - Yellow
    '1': '#2196F3',  // Bus - Blue
    '3': '#9C27B0',  // Metro - Purple
    '11': '#FF5722'  // Trolleybus - Orange
  };

  // Step type labels
  const stepTypeLabels = {
    '-1': 'Walking',
    '0': 'Tram',
    '1': 'Metro',
    '3': 'Bus',
    '11': 'Trolleybus'
  };

  useEffect(() => {
    // Fetch game steps
    const fetchGameSteps = async () => {
      const { data, error } = await supabase
        .from('game_steps')
        .select('*')
        .eq('game_id', gameId)
        .order('step', { ascending: true });

      if (error) {
        console.error('Error fetching game steps:', error);
        return;
      }

      setSteps(data || []);
    };

    fetchGameSteps();
  }, [gameId]);

  useEffect(() => {
    if (!mapContainer.current || steps.length === 0) return;

    // Initialize map
    const map = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [steps[0].end_lng, steps[0].end_lat],
      zoom: 13
    });

    mapRef.current = map;

    map.on('load', () => {
      // Add start marker at the first step end point
      new mapboxgl.Marker({ color: '#4CAF50' })
        .setLngLat([steps[0].end_lng, steps[0].end_lat])
        .setPopup(new mapboxgl.Popup().setHTML('<h3>Start</h3>'))
        .addTo(map);

      // Add end marker at the very last point
      new mapboxgl.Marker({ color: '#F44336' })
        .setLngLat([steps[steps.length - 1].end_lng, steps[steps.length - 1].end_lat])
        .setPopup(new mapboxgl.Popup().setHTML('<h3>End</h3>'))
        .addTo(map);

      // Create a connected path using only end points
      for (let i = 0; i < steps.length - 1; i++) {
        const currentStep = steps[i];
        const nextStep = steps[i+1];
        const color = stepTypeColors[String(nextStep.step_type) as keyof typeof stepTypeColors] || '#000000';
        
        map.addSource(`step-${i}`, {
          type: 'geojson',
          data: {
            type: 'Feature',
            properties: {},
            geometry: {
              type: 'LineString',
              coordinates: [
                [currentStep.end_lng, currentStep.end_lat],
                [nextStep.end_lng, nextStep.end_lat]
              ]
            }
          }
        });

        map.addLayer({
          id: `step-${i}`,
          type: 'line',
          source: `step-${i}`,
          layout: {
            'line-join': 'round',
            'line-cap': 'round'
          },
          paint: {
            'line-color': color,
            'line-width': 4,
            'line-opacity': 0.8
          }
        });
      }

      // Fit bounds to show all steps (using only end points)
      const bounds = new mapboxgl.LngLatBounds();
      steps.forEach(step => {
        bounds.extend([step.end_lng, step.end_lat]);
      });
      map.fitBounds(bounds, { padding: 50 });
    });

    return () => {
      map.remove();
    };
  }, [steps]);

  return (
    <div style={{ position: 'relative', width: '100%', height: '400px' }}>
      <div ref={mapContainer} style={{ width: '100%', height: '100%' }} />
      
      {/* Legend */}
      <div style={{
        position: 'absolute',
        bottom: '20px',
        right: '20px',
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        padding: '10px',
        borderRadius: '4px',
        boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
      }}>
        <h4 style={{ margin: '0 0 10px 0' }}>Transport Types</h4>
        {Object.entries(stepTypeLabels).map(([type, label]) => (
          <div key={type} style={{ display: 'flex', alignItems: 'center', marginBottom: '5px' }}>
            <div style={{
              width: '20px',
              height: '4px',
              backgroundColor: stepTypeColors[type as keyof typeof stepTypeColors],
              marginRight: '8px'
            }} />
            <span>{label}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

export default GameStepsMap; 