import React, { useEffect, useRef, useState, useCallback } 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 { useAuth } from '../../auth/AuthContext';
import './IslandsWorld.css';

/**
 * IslandsWorld: Full-screen metaverse for personal islands
 * Each user has their own floating island in this virtual ocean
 */
export default function IslandsWorld({ theme, onIslandClick, onOpenMap, onOpenPlanets }) {
  const { t } = useTranslation();
  const { authenticated, username } = useAuth();
  const containerRef = useRef(null);
  const mapRef = useRef(null);
  const markersRef = useRef([]);
  const animationRef = useRef(null);

  const [islands, setIslands] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [hoveredIsland, setHoveredIsland] = useState(null);

  // Fetch islands
  useEffect(() => {
    let mounted = true;
    setLoading(true);

    fetchIslands({ limit: 200 })
      .then(data => {
        if (mounted) {
          setIslands(data || []);
          setLoading(false);
        }
      })
      .catch(err => {
        console.warn('[IslandsWorld] Failed to fetch islands:', err);
        if (mounted) setLoading(false);
      });

    return () => { mounted = false; };
  }, []);

  // Filter islands by search
  const filteredIslands = searchQuery
    ? islands.filter(i =>
        (i.username || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
        (i.display_name || '').toLowerCase().includes(searchQuery.toLowerCase())
      )
    : islands;

  // Initialize MapLibre
  useEffect(() => {
    if (!containerRef.current || loading) return;

    const centerLng = 0;
    const centerLat = 0;

    const map = new maplibregl.Map({
      container: containerRef.current,
      style: {
        version: 8,
        sources: {},
        layers: [
          {
            id: 'background',
            type: 'background',
            paint: {
              'background-color': '#0a1628' // Deep ocean
            }
          }
        ]
      },
      center: [centerLng, centerLat],
      zoom: 1,
      pitch: 50,
      bearing: 0,
      antialias: true,
      attributionControl: false
    });

    mapRef.current = map;

    map.on('load', () => {
      // Add ocean gradient layer
      const oceanGradientData = createOceanGradient(centerLng, centerLat);
      map.addSource('ocean-gradient', {
        type: 'geojson',
        data: oceanGradientData
      });

      map.addLayer({
        id: 'ocean-glow',
        type: 'fill',
        source: 'ocean-gradient',
        paint: {
          'fill-color': [
            'interpolate',
            ['linear'],
            ['get', 'intensity'],
            0, '#0a1628',
            0.5, '#0d2847',
            1, '#1e3a5f'
          ],
          'fill-opacity': 0.8
        }
      });

      // Add starfield
      const starsData = createStarfield(500);
      map.addSource('stars', { type: 'geojson', data: starsData });
      map.addLayer({
        id: 'stars',
        type: 'circle',
        source: 'stars',
        paint: {
          'circle-radius': ['interpolate', ['linear'], ['zoom'], 0, 1, 5, 3],
          'circle-color': ['get', 'color'],
          'circle-opacity': ['get', 'opacity'],
          'circle-blur': 0.3
        }
      });

      // Create island markers
      const markers = [];
      const gridSize = Math.ceil(Math.sqrt(filteredIslands.length || 1));
      const spacing = 20;

      filteredIslands.forEach((island, idx) => {
        const gridX = idx % gridSize;
        const gridY = Math.floor(idx / gridSize);
        const baseX = (gridX - gridSize / 2) * spacing;
        const baseY = (gridY - gridSize / 2) * spacing;
        const jitterX = (Math.random() - 0.5) * spacing * 0.4;
        const jitterY = (Math.random() - 0.5) * spacing * 0.4;
        const lng = centerLng + baseX + jitterX;
        const lat = centerLat + baseY + jitterY;

        const el = createIslandMarker(island, idx, t, username);

        el.addEventListener('mouseenter', () => setHoveredIsland(island));
        el.addEventListener('mouseleave', () => setHoveredIsland(null));
        el.addEventListener('click', (e) => {
          e.stopPropagation();
          const action = e.target.closest('[data-action]')?.dataset?.action;
          if (action === 'profile') {
            // Navigate to user profile
            window.location.href = `/profile/${island.username}`;
            return;
          }
          if (action === 'edit') {
            // Navigate to island edit
            window.location.href = `/island/${island.username}/edit`;
            return;
          }
          // Default: open island viewer
          onIslandClick?.(island);
        });

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

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

      markersRef.current = markers;

      // Gentle rotation
      let bearing = 0;
      function animate() {
        bearing += 0.05;
        if (bearing >= 360) bearing = 0;
        map.rotateTo(bearing, { duration: 100 });
        animationRef.current = requestAnimationFrame(animate);
      }
      animate();
    });

    return () => {
      if (animationRef.current) cancelAnimationFrame(animationRef.current);
      markersRef.current.forEach(({ marker }) => marker.remove());
      markersRef.current = [];
      map.remove();
    };
  }, [filteredIslands, loading, onIslandClick, t]);

  return (
    <div className="islands-world">
      {/* Search bar with icon and world nav */}
      <div className="islands-world-search">
        <i className="fa-solid fa-umbrella-beach search-icon" />
        <i className="fa-solid fa-search" />
        <input
          type="text"
          placeholder={t('worlds.searchIslands')}
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        {searchQuery && (
          <button onClick={() => setSearchQuery('')} className="search-clear">
            <i className="fa-solid fa-xmark" />
          </button>
        )}
        <span className="search-count">{islands.length}</span>
        <div className="world-nav-inline">
          <button className="world-nav-btn-sm" onClick={onOpenMap} title={t('worlds.map')}>
            <i className="fa-solid fa-earth-americas" />
          </button>
          <button className="world-nav-btn-sm" onClick={onOpenPlanets} title={t('worlds.planets')}>
            <i className="fa-solid fa-globe" />
          </button>
        </div>
      </div>

      {/* Main canvas */}
      <div ref={containerRef} className="islands-world-canvas" />

      {/* Hovered island tooltip */}
      {hoveredIsland && (
        <div className="islands-world-tooltip">
          <div className="tooltip-avatar">
            {hoveredIsland.avatar_url ? (
              <img src={hoveredIsland.avatar_url} alt={hoveredIsland.username} />
            ) : (
              <span>{(hoveredIsland.username || 'U')[0].toUpperCase()}</span>
            )}
          </div>
          <div className="tooltip-info">
            <div className="tooltip-username">@{hoveredIsland.username}</div>
            <div className="tooltip-bio">{hoveredIsland.display_name || hoveredIsland.bio || t('worlds.clickToVisit')}</div>
            <div className="tooltip-stats">
              {hoveredIsland.content_count || 0} {t('worlds.posts')} • {hoveredIsland.terrain_type || 'tropical'}
            </div>
          </div>
        </div>
      )}

      {/* Create Island CTA (for authenticated users without island) */}
      {authenticated && (
        <button className="islands-world-create" onClick={() => {/* TODO: Create island flow */}}>
          <i className="fa-solid fa-plus" />
          <span>{t('worlds.createIsland')}</span>
        </button>
      )}

      {/* Loading overlay */}
      {loading && (
        <div className="islands-world-loading">
          <div className="loading-spinner" />
          <p>{t('worlds.loadingIslands')}</p>
        </div>
      )}
    </div>
  );
}

/**
 * Create a stylized island marker element
 */
function createIslandMarker(island, idx, t, currentUsername) {
  const el = document.createElement('div');
  el.className = 'island-marker';

  const terrainColors = {
    'tropical': '#2ecc71',
    'desert': '#f39c12',
    'arctic': '#3498db',
    'volcanic': '#e74c3c',
    'meadow': '#27ae60',
  };
  const color = terrainColors[island.terrain_type] || terrainColors['tropical'];
  const seed = island.seed || idx;

  // Generate unique island shape
  const islandSVG = generateIslandSVG(seed, color);
  const postCount = island.content_count || 0;
  const isOwner = currentUsername && island.username &&
    currentUsername.toLowerCase() === island.username.toLowerCase();

  el.innerHTML = `
    <div class="island-marker-inner" style="animation-delay: ${(idx % 12) * 0.25}s;">
      ${islandSVG}
      <div class="island-marker-label">
        <span class="island-marker-name" style="color: ${color}">@${island.username}</span>
        <span class="island-marker-meta">${postCount} posts</span>
      </div>
      <div class="island-marker-actions">
        <button class="island-action-btn island-profile-btn" data-action="profile" title="View Profile">
          <i class="fa-solid fa-user"></i>
        </button>
        ${isOwner ? `
        <button class="island-action-btn island-edit-btn" data-action="edit" title="Edit Island">
          <i class="fa-solid fa-pen"></i>
        </button>
        ` : ''}
      </div>
    </div>
  `;

  return el;
}

/**
 * Generate island SVG with organic shape
 */
function generateIslandSVG(seed, color) {
  const rng = seededRandom(seed);
  const size = 140;
  const cx = size / 2;
  const cy = size / 2;
  const numPoints = 10;

  // Generate organic shape
  const points = [];
  for (let i = 0; i < numPoints; i++) {
    const angle = (i / numPoints) * Math.PI * 2;
    const radiusVar = 0.55 + rng() * 0.45;
    const r = (size / 2.5) * radiusVar;
    points.push({
      x: cx + Math.cos(angle) * r,
      y: cy + Math.sin(angle) * r
    });
  }

  // Create smooth path
  let path = `M ${points[0].x} ${points[0].y}`;
  for (let i = 0; i < numPoints; i++) {
    const curr = points[i];
    const next = points[(i + 1) % numPoints];
    const cpx = (curr.x + next.x) / 2 + (rng() - 0.5) * 10;
    const cpy = (curr.y + next.y) / 2 + (rng() - 0.5) * 10;
    path += ` Q ${cpx} ${cpy} ${next.x} ${next.y}`;
  }
  path += ' Z';

  // Add decorations
  const numTrees = 3 + Math.floor(rng() * 4);
  let trees = '';
  for (let i = 0; i < numTrees; i++) {
    const angle = rng() * Math.PI * 2;
    const dist = 10 + rng() * 20;
    const tx = cx + Math.cos(angle) * dist;
    const ty = cy + Math.sin(angle) * dist;
    const treeSize = 6 + rng() * 6;
    trees += `
      <g transform="translate(${tx}, ${ty})">
        <rect x="-1" y="${-treeSize}" width="2" height="${treeSize}" fill="#5D4037" rx="0.5"/>
        <ellipse cx="0" cy="${-treeSize}" rx="${treeSize * 0.8}" ry="${treeSize * 0.5}" fill="#228B22" opacity="0.9"/>
      </g>
    `;
  }

  return `
    <svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" class="island-svg">
      <defs>
        <radialGradient id="ig-${seed}" cx="30%" cy="30%">
          <stop offset="0%" stop-color="${color}" stop-opacity="1" />
          <stop offset="70%" stop-color="${color}" stop-opacity="0.85" />
          <stop offset="100%" stop-color="${color}" stop-opacity="0.6" />
        </radialGradient>
        <filter id="glow-${seed}">
          <feGaussianBlur stdDeviation="4" result="blur"/>
          <feMerge>
            <feMergeNode in="blur"/>
            <feMergeNode in="SourceGraphic"/>
          </feMerge>
        </filter>
      </defs>
      <!-- Beach ring -->
      <path d="${path}" fill="#F5DEB3" transform="scale(1.08) translate(-5.6, -5.6)" opacity="0.6"/>
      <!-- Main island -->
      <path d="${path}" fill="url(#ig-${seed})" filter="url(#glow-${seed})"/>
      <!-- Trees -->
      ${trees}
    </svg>
  `;
}

/**
 * Create starfield GeoJSON
 */
function createStarfield(count) {
  const features = [];
  for (let i = 0; i < count; i++) {
    const lng = (Math.random() - 0.5) * 400;
    const lat = (Math.random() - 0.5) * 400;
    const brightness = Math.random();
    features.push({
      type: 'Feature',
      geometry: { type: 'Point', coordinates: [lng, lat] },
      properties: {
        color: brightness > 0.8 ? '#ffeedd' : brightness > 0.5 ? '#aaccff' : '#ffffff',
        opacity: 0.3 + brightness * 0.5
      }
    });
  }
  return { type: 'FeatureCollection', features };
}

/**
 * Create ocean gradient GeoJSON
 */
function createOceanGradient(centerLng, centerLat) {
  const features = [];
  const rings = 10;
  for (let i = 0; i < rings; i++) {
    const radius = (i + 1) * 30;
    const coords = [];
    for (let j = 0; j <= 64; j++) {
      const angle = (j / 64) * Math.PI * 2;
      coords.push([
        centerLng + Math.cos(angle) * radius,
        centerLat + Math.sin(angle) * radius
      ]);
    }
    features.push({
      type: 'Feature',
      geometry: { type: 'Polygon', coordinates: [coords] },
      properties: { intensity: 1 - (i / rings) }
    });
  }
  return { type: 'FeatureCollection', features };
}

/**
 * Seeded random number generator
 */
function seededRandom(seed) {
  let s = seed;
  return function() {
    s = (s * 9301 + 49297) % 233280;
    return s / 233280;
  };
}
