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.5, // Zoomed out more to see spread islands
      pitch: 65, // 3D angle
      bearing: 0,
      antialias: true,
      attributionControl: false
    });

    mapRef.current = map;

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

      // Use grid-based positioning to prevent overlap
      const gridSize = Math.ceil(Math.sqrt(islands.length));
      const spacing = 8; // degrees between islands

      islands.forEach((island, idx) => {
        // Grid position with random offset for organic feel
        const gridX = idx % gridSize;
        const gridY = Math.floor(idx / gridSize);
        const baseX = (gridX - gridSize / 2) * spacing;
        const baseY = (gridY - gridSize / 2) * spacing;
        // Add controlled randomness within cell
        const jitterX = (Math.random() - 0.5) * spacing * 0.6;
        const jitterY = (Math.random() - 0.5) * spacing * 0.6;
        const lng = centerLng + baseX + jitterX;
        const lat = centerLat + baseY + jitterY;

        // 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);

        const postCount = island.content_count || 0;
        const terrain = island.terrain_type || 'tropical';

        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 % 10) * 0.3}s;
            filter: drop-shadow(0 0 20px ${terrainColor}bb) drop-shadow(0 12px 30px rgba(0,0,0,0.7));
          ">
            ${islandSVG}
            <!-- Island info card -->
            <div style="
              position: absolute;
              bottom: -35px;
              left: 50%;
              transform: translateX(-50%);
              background: linear-gradient(135deg, rgba(15, 23, 42, 0.98), rgba(30, 41, 59, 0.95));
              color: white;
              padding: 6px 12px;
              border-radius: 12px;
              font-size: 11px;
              font-weight: 700;
              white-space: nowrap;
              border: 1px solid ${terrainColor}66;
              text-shadow: 0 1px 2px rgba(0,0,0,0.5);
              box-shadow: 0 4px 16px rgba(0,0,0,0.5), 0 0 12px ${terrainColor}33;
              backdrop-filter: blur(8px);
              display: flex;
              flex-direction: column;
              align-items: center;
              gap: 2px;
            ">
              <span style="color: ${terrainColor}; font-size: 12px;">@${island.username}</span>
              <span style="font-size: 9px; color: rgba(255,255,255,0.7); font-weight: 500;">
                ${postCount} posts • ${terrain}
              </span>
            </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 detailed island SVG shape (bigger, more features)
 */
function generateMiniIsland(seed, terrainColor) {
  // Seeded random
  const rng = () => {
    seed = (seed * 9301 + 49297) % 233280;
    return seed / 233280;
  };

  // Much bigger island
  const size = 120;
  const centerX = size / 2;
  const centerY = size / 2;
  const numPoints = 12;

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

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

  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) * 8;
    const controlY = (current.y + next.y) / 2 + (rng() - 0.5) * 8;
    path += ` Q ${controlX} ${controlY} ${next.x} ${next.y}`;
  }
  path += ' Z';

  // Beach ring
  let beachPath = '';
  const beachPoints = [];
  for (let i = 0; i < numPoints; i++) {
    const angle = (i / numPoints) * Math.PI * 2;
    const radiusVariation = 0.72 + rng() * 0.45;
    const radius = (size / 2.1) * radiusVariation;
    beachPoints.push({
      x: centerX + Math.cos(angle) * radius,
      y: centerY + Math.sin(angle) * radius
    });
  }
  beachPath = `M ${beachPoints[0].x} ${beachPoints[0].y}`;
  for (let i = 0; i < numPoints; i++) {
    const current = beachPoints[i];
    const next = beachPoints[(i + 1) % numPoints];
    beachPath += ` Q ${(current.x + next.x) / 2} ${(current.y + next.y) / 2} ${next.x} ${next.y}`;
  }
  beachPath += ' Z';

  // Trees (more, varied sizes)
  const numTrees = 5 + Math.floor(rng() * 6);
  let trees = '';
  for (let i = 0; i < numTrees; i++) {
    const angle = rng() * Math.PI * 2;
    const dist = 8 + rng() * 25;
    const tx = centerX + Math.cos(angle) * dist;
    const ty = centerY + Math.sin(angle) * dist;
    const treeHeight = 8 + rng() * 10;
    const treeWidth = 4 + rng() * 4;
    // Palm tree shape
    trees += `
      <g transform="translate(${tx}, ${ty})">
        <rect x="${-1}" y="${-treeHeight}" width="2" height="${treeHeight}" fill="#5D4037" rx="1"/>
        <ellipse cx="0" cy="${-treeHeight}" rx="${treeWidth}" ry="${treeWidth * 0.6}" fill="#228B22" opacity="0.9"/>
        <ellipse cx="${-treeWidth * 0.5}" cy="${-treeHeight + 2}" rx="${treeWidth * 0.7}" ry="${treeWidth * 0.4}" fill="#2E7D32" opacity="0.8"/>
      </g>
    `;
  }

  // Small buildings/huts
  const numHuts = 1 + Math.floor(rng() * 2);
  let huts = '';
  for (let i = 0; i < numHuts; i++) {
    const angle = rng() * Math.PI * 2;
    const dist = 10 + rng() * 15;
    const hx = centerX + Math.cos(angle) * dist;
    const hy = centerY + Math.sin(angle) * dist;
    huts += `
      <g transform="translate(${hx}, ${hy})">
        <rect x="-5" y="-6" width="10" height="8" fill="#8D6E63" rx="1"/>
        <polygon points="-7,-6 0,-12 7,-6" fill="#D32F2F"/>
      </g>
    `;
  }

  // Water sparkles
  let sparkles = '';
  for (let i = 0; i < 6; i++) {
    const sx = rng() * size;
    const sy = rng() * size;
    sparkles += `<circle cx="${sx}" cy="${sy}" r="1.5" fill="white" opacity="${0.3 + rng() * 0.4}"/>`;
  }

  return `
    <svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" style="overflow: visible;">
      <defs>
        <radialGradient id="island-grad-${seed}" cx="30%" cy="30%">
          <stop offset="0%" stop-color="${terrainColor}" stop-opacity="1" />
          <stop offset="60%" stop-color="${terrainColor}" stop-opacity="0.95" />
          <stop offset="100%" stop-color="${terrainColor}" stop-opacity="0.8" />
        </radialGradient>
        <radialGradient id="beach-grad-${seed}" cx="50%" cy="50%">
          <stop offset="0%" stop-color="#F5DEB3" stop-opacity="0.9" />
          <stop offset="100%" stop-color="#DEB887" stop-opacity="0.7" />
        </radialGradient>
        <filter id="glow-${seed}">
          <feGaussianBlur stdDeviation="2" result="coloredBlur"/>
          <feMerge>
            <feMergeNode in="coloredBlur"/>
            <feMergeNode in="SourceGraphic"/>
          </feMerge>
        </filter>
      </defs>
      <!-- Ocean sparkles -->
      ${sparkles}
      <!-- Beach ring -->
      <path d="${beachPath}" fill="url(#beach-grad-${seed})" stroke="rgba(255,255,255,0.2)" stroke-width="1" />
      <!-- Main island -->
      <path d="${path}" fill="url(#island-grad-${seed})" stroke="rgba(255,255,255,0.35)" stroke-width="2" filter="url(#glow-${seed})" />
      <!-- Buildings -->
      ${huts}
      <!-- Trees -->
      ${trees}
    </svg>
  `;
}
