import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

let scene, camera, renderer, map, controls;
let worldData;
let worldDataLoaded = false;
let highlightColor = 0xFFFF00; // 默认高亮颜色
let currentMapType = 'standard';
const mapTextures = {
    standard: '/static/images/eo_base_2020_clean_3600x1800.png',
    night: '/static/images/BlackMarble_2016_01deg.jpg',
    gray: '/static/images/world.oceanmask.5400x2700.png',
    satellite: '/static/images/world.topo.bathy.200412.3x5400x2700.jpg'
};

let countries = [];

export function init() {
    scene = new THREE.Scene();
    const aspect = window.innerWidth / window.innerHeight;
    const frustumSize = 180;
    camera = new THREE.OrthographicCamera(
        frustumSize * aspect / -2, frustumSize * aspect / 2,
        frustumSize / 2, frustumSize / -2,
        0.1, 1000
    );
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.getElementById('map').appendChild(renderer.domElement);

    const mapTexture = new THREE.TextureLoader().load(mapTextures[currentMapType]);
    const material = new THREE.MeshBasicMaterial({ map: mapTexture });
    map = new THREE.Mesh(new THREE.PlaneGeometry(360, 180), material);
    scene.add(map);

    camera.position.z = 100;

    controls = new OrbitControls(camera, renderer.domElement);
    controls.enableRotate = false;
    controls.enablePan = true;
    controls.enableZoom = true;
    controls.update();

    setupControls();
    setupColorPicker();
    setupMapSelection();

    loadWorldData();
    animate();
    loadAllCountries();
    setupAutocomplete();

    window.addEventListener('resize', onWindowResize, false);
}

export function loadSharedMap(mapData) {
    const { countries: sharedCountries, highlight_color, map_type } = mapData;

    changeMapType(map_type);
    setHighlightColor(parseInt(highlight_color, 16));

    countries = sharedCountries;
    updateCountryList();
    countries.forEach(country => highlightCountry(country));
}

export function addCountry() {
    const input = document.getElementById('new-country');
    const country = input.value.trim();
    if (country && !countries.includes(country)) {
        countries.push(country);
        updateCountryList();
        highlightCountry(country);
        input.value = '';
    }
}

export function removeCountry(country) {
    countries = countries.filter(c => c !== country);
    updateCountryList();
    updateHighlights();
}

export function shareMap() {
    const mapData = {
        countries: countries,
        highlight_color: highlightColor.toString(16),
        map_type: currentMapType
    };

    fetch('/share_map', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(mapData),
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const shareUrl = window.location.origin + data.share_url;
            alert(`新的共享地图已创建。分享链接：${shareUrl}`);
            window.location.href = data.share_url; // 重定向到新的共享地图
        } else {
            alert('创建共享地图失败，请重试。');
        }
    })
    .catch(error => {
        console.error('Error sharing map:', error);
        alert('创建共享地图失败，请重试。');
    });
}

function updateCountryList() {
    const ul = document.getElementById('countries');
    ul.innerHTML = '';
    countries.forEach(country => {
        const li = document.createElement('li');
        li.className = 'flex justify-between items-center bg-gray-800 p-2 rounded';
        const span = document.createElement('span');
        span.textContent = country;
        span.className = 'text-gray-200';
        li.appendChild(span);
        const removeButton = document.createElement('button');
        removeButton.textContent = '删除';
        removeButton.className = 'bg-red-600 text-white px-2 py-1 rounded text-sm hover:bg-red-700 transition duration-200';
        removeButton.onclick = () => removeCountry(country);
        li.appendChild(removeButton);
        ul.appendChild(li);
    });
}

function changeMapType(mapType) {
    if (mapType !== currentMapType) {
        currentMapType = mapType;
        const newTexture = new THREE.TextureLoader().load(mapTextures[mapType]);
        map.material.map = newTexture;
        map.material.needsUpdate = true;
    }
}

function setHighlightColor(color) {
    highlightColor = color;
}

function highlightCountry(countryName) {
    if (!worldDataLoaded) {
        console.log('World data not loaded yet. Skipping highlight for:', countryName);
        return;
    }
    const feature = worldData.features.find(f => f.properties.ADMIN.toLowerCase() === countryName.toLowerCase());
    if (feature) {
        const material = new THREE.MeshBasicMaterial({
            color: highlightColor,
            transparent: true,
            opacity: 0.5,
            side: THREE.DoubleSide,
            depthWrite: false,
            depthTest: false
        });
        if (feature.geometry.type === "Polygon") {
            const mesh = createPolygonMesh(feature.geometry.coordinates[0], material);
            scene.add(mesh);
        } else if (feature.geometry.type === "MultiPolygon") {
            feature.geometry.coordinates.forEach(polygon => {
                const mesh = createPolygonMesh(polygon[0], material);
                scene.add(mesh);
            });
        }
    }
}

function createPolygonMesh(coords, material) {
    const shape = new THREE.Shape();
    coords.forEach((coord, index) => {
        if (index === 0) {
            shape.moveTo(coord[0], coord[1]);
        } else {
            shape.lineTo(coord[0], coord[1]);
        }
    });
    const geometry = new THREE.ShapeGeometry(shape);
    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.z = 0.1;
    return mesh;
}

function loadWorldData() {
    fetch('https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson')
        .then(response => response.json())
        .then(data => {
            worldData = data;
            worldDataLoaded = true;
        });
}

function onWindowResize() {
    const aspect = window.innerWidth / window.innerHeight;
    const frustumSize = 180;
    camera.left = -frustumSize * aspect / 2;
    camera.right = frustumSize * aspect / 2;
    camera.top = frustumSize / 2;
    camera.bottom = -frustumSize / 2;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate() {
    requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
}

function setupControls() {
    // 实现控制设置
}

function setupColorPicker() {
    // 实现颜色选择器设置
}

function setupMapSelection() {
    // 实现地图类型选择设置
}

function loadAllCountries() {
    // 实现加载所有国家的功能
}

function setupAutocomplete() {
    // 实现自动完成功能
}

function updateHighlights() {
    // 实现更新高亮的功能
}
