import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';
import { fetchIslands } from '../../api/client';
import '../../styles/universe.css';

/**
 * IslandUniverse: View all user islands floating in virtual space using MapLibre 3D
 * Lightweight alternative to Three.js - uses existing MapLibre dependency
 */
export default function IslandUniverse({ onClose, onIslandClick }) {
  const { t } = useTranslation();
  const containerRef = useRef(null);
  const mapRef = useRef(null);
  const markersRef = useRef([]);
  const [islands, setIslands] = useState([]);
  const [hoveredIsland, setHoveredIsland] = useState(null);

  // Fetch all islands
  useEffect(() => {
    fetchIslands({ limit: 100 }).then(islandData => {
      console.log('[IslandUniverse] Loaded', islandData.length, 'islands');
      setIslands(islandData);
    });
  }, []);

  useEffect(() => {
    if (!containerRef.current || islands.length === 0) return;

    console.log('[IslandUniverse] Rendering universe with MapLibre:', islands.length, 'islands');

    // Center point in virtual space
    const centerLat = 0;
    const centerLng = 0;

    // Create MapLibre map with space theme
    const map = new maplibregl.Map({
      container: containerRef.current,
      style: {
        version: 8,
        sources: {},
        layers: [
          {
            id: 'background',
            type: 'background',
            paint: {
              'background-color': '#000510' // Deep space
            }
          }
        ]
      },
      center: [centerLng, centerLat],
      zoom: 0.8,
      pitch: 70, // 3D angle
      bearing: 0,
      antialias: true,
      attributionControl: false
    });

    mapRef.current = map;

    map.on('load', () => {
      // Create island markers
      const markers = [];

      islands.forEach((island, idx) => {
        // Truly scatter islands randomly across wide area
        const randomAngle = Math.random() * Math.PI * 2;
        const randomRadius = 5 + Math.random() * 15; // Large random radius 5-20 degrees
        const randomOffsetX = (Math.random() - 0.5) * 10; // Additional random scatter
        const randomOffsetY = (Math.random() - 0.5) * 10;
        const lng = centerLng + Math.cos(randomAngle) * randomRadius + randomOffsetX;
        const lat = centerLat + Math.sin(randomAngle) * randomRadius + randomOffsetY;

        // Create marker element
        const el = document.createElement('div');
        el.className = 'universe-island-marker';

        const terrainColor = getTerrainColor(island.terrain_type);

        const islandSVG = generateMiniIsland(island.seed || idx, terrainColor);

        el.innerHTML = `
          <div class="universe-island-shape" style="
            position: relative;
            cursor: pointer;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            animation: universeIslandFloat 6s ease-in-out infinite;
            animation-delay: ${idx * 0.5}s;
            filter: drop-shadow(0 0 15px ${terrainColor}aa) drop-shadow(0 8px 20px rgba(0,0,0,0.6));
          ">
            ${islandSVG}
            <div style="
              position: absolute;
              bottom: -18px;
              left: 50%;
              transform: translateX(-50%);
              background: rgba(20, 30, 50, 0.95);
              color: white;
              padding: 2px 8px;
              border-radius: 8px;
              font-size: 10px;
              font-weight: 600;
              white-space: nowrap;
              border: 1px solid rgba(255,255,255,0.25);
              text-shadow: 0 1px 2px rgba(0,0,0,0.5);
              box-shadow: 0 2px 8px rgba(0,0,0,0.4);
            ">@${island.username}</div>
          </div>
        `;

        // Hover effect
        el.addEventListener('mouseenter', () => {
          el.querySelector('.universe-island-shape').style.transform = 'scale(1.25) translateY(-8px)';
          el.querySelector('.universe-island-shape').style.filter = `drop-shadow(0 0 30px ${terrainColor}ff) drop-shadow(0 15px 35px rgba(0,0,0,0.8))`;
          setHoveredIsland(island);
        });

        el.addEventListener('mouseleave', () => {
          el.querySelector('.universe-island-shape').style.transform = 'scale(1)';
          el.querySelector('.universe-island-shape').style.filter = `drop-shadow(0 0 15px ${terrainColor}aa) drop-shadow(0 8px 20px rgba(0,0,0,0.6))`;
          setHoveredIsland(null);
        });

        // Click handler
        el.addEventListener('click', (e) => {
          e.stopPropagation();
          console.log('[IslandUniverse] Clicked island:', island.username);
          onIslandClick && onIslandClick(island);
        });

        // Create marker
        const marker = new maplibregl.Marker({
          element: el,
          anchor: 'center'
        })
          .setLngLat([lng, lat])
          .addTo(map);

        markers.push({ marker, island, el });
      });

      markersRef.current = markers;

      // Slow rotation animation
      let bearing = 0;
      function rotateCamera() {
        bearing += 0.1;
        if (bearing >= 360) bearing = 0;
        map.rotateTo(bearing, { duration: 100 });
        requestAnimationFrame(rotateCamera);
      }
      rotateCamera();

      // Add starfield effect with custom layer
      map.addLayer({
        id: 'stars',
        type: 'circle',
        source: {
          type: 'geojson',
          data: createStarfieldGeoJSON(centerLng, centerLat, 500)
        },
        paint: {
          'circle-radius': ['interpolate', ['linear'], ['zoom'], 0, 0.5, 10, 2],
          'circle-color': [
            'case',
            ['<', ['random'], 0.7], '#ffffff',
            ['<', ['random'], 0.9], '#aabbff',
            '#ffeeaa'
          ],
          'circle-opacity': 0.8,
          'circle-blur': 0.2
        }
      });
    });

    // Cleanup
    return () => {
      markersRef.current.forEach(({ marker }) => marker.remove());
      markersRef.current = [];
      map.remove();
    };
  }, [islands, onIslandClick]);

  return (
    <div className="island-universe-modal" onClick={onClose}>
      <div className="island-universe-container" onClick={(e) => e.stopPropagation()}>
        <button className="island-universe-close" onClick={onClose}>×</button>

        <div className="island-universe-header">
          <h1>🌌 {t('universe.title')}</h1>
          <p>{t('universe.islandsCount', { count: islands.length })}</p>
        </div>

        <div
          ref={containerRef}
          className="island-universe-canvas"
          style={{ width: '100%', height: '700px' }}
        />

        {hoveredIsland && (
          <div className="island-universe-tooltip">
            <div className="tooltip-username">@{hoveredIsland.username}</div>
            <div className="tooltip-bio">{hoveredIsland.display_name || hoveredIsland.bio || t('universe.clickToVisit')}</div>
            <div className="tooltip-stats">
              {hoveredIsland.content_count} {t('universe.posts')} • {hoveredIsland.terrain_type}
            </div>
          </div>
        )}

        <div className="island-universe-help">
          <p>🖱️ {t('universe.help')}</p>
        </div>
      </div>
    </div>
  );
}

/**
 * Create starfield as GeoJSON for MapLibre
 */
function createStarfieldGeoJSON(centerLng, centerLat, count) {
  const features = [];

  for (let i = 0; i < count; i++) {
    const lng = centerLng + (Math.random() - 0.5) * 20;
    const lat = centerLat + (Math.random() - 0.5) * 20;

    features.push({
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: [lng, lat]
      },
      properties: {
        brightness: Math.random()
      }
    });
  }

  return {
    type: 'FeatureCollection',
    features
  };
}

/**
 * Get terrain color as CSS color string
 */
function getTerrainColor(terrainType) {
  const palettes = {
    'tropical': '#2ecc71',
    'desert': '#f39c12',
    'arctic': '#3498db',
    'volcanic': '#e74c3c',
    'meadow': '#27ae60',
  };
  return palettes[terrainType] || palettes['tropical'];
}

/**
 * Generate a mini island SVG shape (organic, irregular)
 */
function generateMiniIsland(seed, terrainColor) {
  // Seeded random
  const rng = () => {
    seed = (seed * 9301 + 49297) % 233280;
    return seed / 233280;
  };

  // Generate organic island shape using bezier curves
  const size = 50;
  const centerX = size / 2;
  const centerY = size / 2;
  const numPoints = 8;

  let path = '';
  const points = [];

  for (let i = 0; i < numPoints; i++) {
    const angle = (i / numPoints) * Math.PI * 2;
    const radiusVariation = 0.7 + rng() * 0.6; // Random radius
    const radius = (size / 2) * radiusVariation;
    const x = centerX + Math.cos(angle) * radius;
    const y = centerY + Math.sin(angle) * radius;
    points.push({ x, y });
  }

  // Create smooth curve using quadratic bezier
  path = `M ${points[0].x} ${points[0].y}`;
  for (let i = 0; i < numPoints; i++) {
    const current = points[i];
    const next = points[(i + 1) % numPoints];
    const controlX = (current.x + next.x) / 2 + (rng() - 0.5) * 5;
    const controlY = (current.y + next.y) / 2 + (rng() - 0.5) * 5;
    path += ` Q ${controlX} ${controlY} ${next.x} ${next.y}`;
  }
  path += ' Z';

  // Add some trees/details
  const numTrees = 2 + Math.floor(rng() * 3);
  let trees = '';
  for (let i = 0; i < numTrees; i++) {
    const tx = centerX + (rng() - 0.5) * (size * 0.4);
    const ty = centerY + (rng() - 0.5) * (size * 0.4);
    const treeSize = 3 + rng() * 2;
    trees += `<circle cx="${tx}" cy="${ty}" r="${treeSize}" fill="rgba(0,80,0,0.6)" />`;
  }

  return `
    <svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" style="overflow: visible;">
      <defs>
        <radialGradient id="island-grad-${seed}" cx="35%" cy="35%">
          <stop offset="0%" stop-color="${terrainColor}" stop-opacity="1" />
          <stop offset="70%" stop-color="${terrainColor}" stop-opacity="0.9" />
          <stop offset="100%" stop-color="${terrainColor}" stop-opacity="0.7" />
        </radialGradient>
      </defs>
      <!-- Island shape -->
      <path d="${path}" fill="url(#island-grad-${seed})" stroke="rgba(255,255,255,0.3)" stroke-width="1.5" />
      <!-- Trees/details -->
      ${trees}
    </svg>
  `;
}
