#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
地圖生成器 v2.0

使用 mock 資料重新生成 Folium 地圖
- 含街景側邊面板
- 含圖層篩選功能
"""

import json
from pathlib import Path

import folium
from folium import FeatureGroup


def load_mock_data():
    """載入 mock 資料"""
    script_dir = Path(__file__).parent
    mock_file = script_dir / 'mock_properties_data.json'

    with open(mock_file, 'r', encoding='utf-8') as f:
        return json.load(f)


def get_value_category(value):
    """根據估值分類"""
    if value is None or value == 0:
        return 'unknown', 'gray', '未知'
    value_billion = value / 1e8
    if value_billion >= 100:
        return 'over100', 'red', '超過 100 億'
    elif value_billion >= 50:
        return '50to100', 'orange', '50-100 億'
    elif value_billion >= 10:
        return '10to50', 'blue', '10-50 億'
    elif value_billion >= 1:
        return '1to10', 'green', '1-10 億'
    else:
        return 'under1', 'lightgray', '未滿 1 億'


def format_value(value):
    """格式化金額顯示"""
    if value is None or value == 0:
        return "N/A"
    if value >= 1e8:
        return f"{value / 1e8:.2f} 億元"
    elif value >= 1e4:
        return f"{value / 1e4:.0f} 萬元"
    else:
        return f"{value:.0f} 元"


def create_popup_html(prop):
    """建立 popup HTML 內容（含街景按鈕）"""
    value = prop.get('value_investment', 0) or 0
    value_str = format_value(value)

    area = prop.get('area', 0) or 0
    area_str = f"{area:,.1f} 坪" if area else "N/A"

    appraisers = prop.get('appraisers', [])
    appraisers_str = ', '.join(appraisers) if appraisers else "N/A"

    lat = prop.get('latitude', 0)
    lng = prop.get('longitude', 0)
    name = prop['name'].replace("'", "\\'")
    address = prop['address'].replace("'", "\\'")

    html = f"""
    <div style="font-family: Arial, sans-serif; min-width: 220px;">
        <h4 style="margin: 0 0 8px 0; color: #333; font-size: 14px;">{prop['name']}</h4>
        <table style="font-size: 12px; border-collapse: collapse; width: 100%;">
            <tr>
                <td style="padding: 3px 8px 3px 0; color: #666;">代號:</td>
                <td style="padding: 3px 0;">{prop['code']}</td>
            </tr>
            <tr>
                <td style="padding: 3px 8px 3px 0; color: #666;">區域:</td>
                <td style="padding: 3px 0;">{prop['city']}</td>
            </tr>
            <tr>
                <td style="padding: 3px 8px 3px 0; color: #666;">地址:</td>
                <td style="padding: 3px 0;">{prop['address']}</td>
            </tr>
            <tr>
                <td style="padding: 3px 8px 3px 0; color: #666;">面積:</td>
                <td style="padding: 3px 0; font-weight: bold; color: #1976d2;">{area_str}</td>
            </tr>
            <tr>
                <td style="padding: 3px 8px 3px 0; color: #666;">估值:</td>
                <td style="padding: 3px 0; font-weight: bold; color: #e03131;">{value_str}</td>
            </tr>
            <tr>
                <td style="padding: 3px 8px 3px 0; color: #666;">估價師:</td>
                <td style="padding: 3px 0;">{appraisers_str}</td>
            </tr>
        </table>
        <div style="margin-top: 10px;">
            <button onclick="openStreetView({lat}, {lng}, '{address}', '{name}')"
                    style="background: #4285f4; color: white; border: none;
                           padding: 8px 16px; border-radius: 4px; cursor: pointer;
                           font-size: 12px; width: 100%;">
                🗺️ 街景檢視
            </button>
        </div>
    </div>
    """
    return html


def generate_map(data, output_path):
    """生成地圖"""
    # 過濾有座標的資料
    valid_data = [p for p in data if p.get('latitude') and p.get('longitude')]

    if not valid_data:
        print("沒有有效的座標資料！")
        return

    # 計算中心點
    avg_lat = sum(p['latitude'] for p in valid_data) / len(valid_data)
    avg_lon = sum(p['longitude'] for p in valid_data) / len(valid_data)

    # 建立地圖
    m = folium.Map(
        location=[avg_lat, avg_lon],
        zoom_start=8,
        tiles='OpenStreetMap'
    )

    # 建立估值分類圖層
    value_layers = {
        'over100': FeatureGroup(name='💰 超過 100 億', show=True),
        '50to100': FeatureGroup(name='💰 50-100 億', show=True),
        '10to50': FeatureGroup(name='💰 10-50 億', show=True),
        '1to10': FeatureGroup(name='💰 1-10 億', show=True),
        'under1': FeatureGroup(name='💰 未滿 1 億', show=True),
        'unknown': FeatureGroup(name='💰 未知', show=True),
    }

    # 統計各分類數量
    value_counts = {k: 0 for k in value_layers.keys()}

    # 添加標記
    for prop in valid_data:
        lat = prop['latitude']
        lon = prop['longitude']
        value = prop.get('value_investment', 0) or 0

        value_category, color, _ = get_value_category(value)
        value_counts[value_category] += 1

        popup_html = create_popup_html(prop)

        folium.Marker(
            location=[lat, lon],
            popup=folium.Popup(popup_html, max_width=300),
            tooltip=f"{prop['name']} ({prop['city']})",
            icon=folium.Icon(color=color, icon='building', prefix='fa')
        ).add_to(value_layers[value_category])

    # 將圖層加入地圖
    for layer in value_layers.values():
        layer.add_to(m)

    # 添加圖層控制
    folium.LayerControl(collapsed=False).add_to(m)

    # 添加街景面板 CSS 和 HTML
    street_view_panel = '''
    <style>
    .sv-panel {
        position: fixed;
        right: -400px;
        top: 0;
        width: 400px;
        min-width: 300px;
        max-width: 90vw;
        height: 100vh;
        background-color: white;
        border-left: 2px solid #ccc;
        box-shadow: -2px 0 10px rgba(0,0,0,0.2);
        z-index: 10000;
        transition: right 0.3s ease;
        overflow-y: auto;
        font-family: Arial, sans-serif;
    }
    .sv-panel.open { right: 0; }
    .sv-resize-handle {
        position: absolute; left: 0; top: 0;
        width: 5px; height: 100%;
        cursor: ew-resize; background-color: transparent; z-index: 10001;
    }
    .sv-resize-handle:hover { background-color: rgba(66, 133, 244, 0.3); }
    .sv-close {
        position: absolute; top: 10px; right: 15px;
        font-size: 24px; cursor: pointer; color: #666;
    }
    .sv-close:hover { color: #000; }
    .sv-header {
        padding: 15px; border-bottom: 2px solid #eee;
        font-weight: bold; font-size: 14px; color: #333;
    }
    .sv-content { padding: 15px; }
    .sv-tabs { display: flex; border-bottom: 1px solid #ddd; margin-bottom: 15px; }
    .sv-tab {
        flex: 1; padding: 10px; text-align: center; cursor: pointer;
        background-color: #f5f5f5; border: none; font-size: 12px; color: #666;
    }
    .sv-tab.active { background-color: #4285F4; color: white; font-weight: bold; }
    .sv-tab-content { display: none; }
    .sv-tab-content.active { display: block; }
    .sv-iframe { width: 100%; height: 450px; border: none; border-radius: 3px; }
    .building-info-section { margin-bottom: 12px; }
    .building-info-label { font-weight: bold; color: #333; font-size: 12px; margin-bottom: 3px; }
    .building-info-value { color: #666; font-size: 13px; }
    </style>

    <div id="svPanel" class="sv-panel">
        <div class="sv-resize-handle" id="resizeHandle"></div>
        <span class="sv-close" onclick="closeStreetView()">&times;</span>
        <div class="sv-header">
            <div id="svTitle">街景檢視</div>
        </div>
        <div class="sv-tabs">
            <button class="sv-tab active" onclick="switchTab(event, 'streetview')">街景</button>
            <button class="sv-tab" onclick="switchTab(event, 'building')">標的資訊</button>
        </div>
        <div class="sv-content">
            <div id="streetview" class="sv-tab-content active">
                <iframe id="svIframe" class="sv-iframe"></iframe>
            </div>
            <div id="building" class="sv-tab-content">
                <div class="building-info-section">
                    <div class="building-info-label">標的名稱</div>
                    <div class="building-info-value" id="buildingName">-</div>
                </div>
                <div class="building-info-section">
                    <div class="building-info-label">位址</div>
                    <div class="building-info-value" id="buildingAddr">-</div>
                </div>
                <div class="building-info-section">
                    <div class="building-info-label">資料說明</div>
                    <div class="building-info-value" style="color: #999; font-style: italic;">
                        此為 Demo 展示用假資料<br>
                        座標已隨機偏移處理<br>
                        街景僅供功能展示
                    </div>
                </div>
            </div>
        </div>
    </div>
    '''
    m.get_root().html.add_child(folium.Element(street_view_panel))

    # 添加街景功能的 JavaScript
    street_view_js = '''
    <script>
    function openStreetView(lat, lng, address, buildingName) {
        var title = buildingName || address;
        document.getElementById('svTitle').textContent = title;
        document.getElementById('svIframe').src =
            'https://www.google.com/maps?layer=c&cbll=' + lat + ',' + lng +
            '&cbp=12,0,0,0,0&source=outdoor&output=svembed';
        document.getElementById('buildingName').textContent = title;
        document.getElementById('buildingAddr').textContent = address;
        document.getElementById('svPanel').classList.add('open');
    }

    function closeStreetView() {
        document.getElementById('svPanel').classList.remove('open');
    }

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' || e.key === 'Esc') {
            var panel = document.getElementById('svPanel');
            if (panel && panel.classList.contains('open')) {
                closeStreetView();
            }
        }
    });

    (function() {
        var panel = document.getElementById('svPanel');
        var handle = document.getElementById('resizeHandle');
        if (!panel || !handle) return;

        var isResizing = false;
        var startX = 0;
        var startWidth = 0;

        handle.addEventListener('mousedown', function(e) {
            isResizing = true;
            startX = e.clientX;
            startWidth = panel.offsetWidth;
            document.body.style.cursor = 'ew-resize';
            document.body.style.userSelect = 'none';
            e.preventDefault();
        });

        document.addEventListener('mousemove', function(e) {
            if (!isResizing) return;
            var deltaX = startX - e.clientX;
            var newWidth = startWidth + deltaX;
            if (newWidth >= 300 && newWidth <= window.innerWidth * 0.9) {
                panel.style.width = newWidth + 'px';
            }
        });

        document.addEventListener('mouseup', function() {
            if (isResizing) {
                isResizing = false;
                document.body.style.cursor = '';
                document.body.style.userSelect = '';
            }
        });
    })();

    function switchTab(event, tabName) {
        document.querySelectorAll('.sv-tab-content').forEach(function(el) {
            el.classList.remove('active');
        });
        document.querySelectorAll('.sv-tab').forEach(function(el) {
            el.classList.remove('active');
        });
        document.getElementById(tabName).classList.add('active');
        event.target.classList.add('active');
    }
    </script>
    '''
    m.get_root().html.add_child(folium.Element(street_view_js))

    # 添加圖例（放在左下角，避免和右上角的圖層控制重疊）
    legend_html = f'''
    <div style="position: fixed; bottom: 30px; left: 10px; width: 260px;
                background-color: white; border: 2px solid grey;
                border-radius: 5px; padding: 12px; z-index: 9999;
                font-size: 13px; font-family: Arial, sans-serif;
                box-shadow: 0 0 15px rgba(0,0,0,0.2);">
        <div style="font-weight: bold; margin-bottom: 10px; border-bottom: 2px solid #333;
                    padding-bottom: 5px; color: #333;">
            投資組合 Demo - 估值分級
        </div>
        <div style="margin: 8px 0; display: flex; align-items: center; justify-content: space-between;">
            <div style="display: flex; align-items: center;">
                <i class="fa fa-map-marker" style="color: red; font-size: 14px; margin-right: 8px;"></i>
                <span>超過 100 億元</span>
            </div>
            <span style="font-weight: bold; color: #d32f2f;">{value_counts['over100']}</span>
        </div>
        <div style="margin: 8px 0; display: flex; align-items: center; justify-content: space-between;">
            <div style="display: flex; align-items: center;">
                <i class="fa fa-map-marker" style="color: orange; font-size: 14px; margin-right: 8px;"></i>
                <span>50-100 億元</span>
            </div>
            <span style="font-weight: bold; color: #f57c00;">{value_counts['50to100']}</span>
        </div>
        <div style="margin: 8px 0; display: flex; align-items: center; justify-content: space-between;">
            <div style="display: flex; align-items: center;">
                <i class="fa fa-map-marker" style="color: blue; font-size: 14px; margin-right: 8px;"></i>
                <span>10-50 億元</span>
            </div>
            <span style="font-weight: bold; color: #1976d2;">{value_counts['10to50']}</span>
        </div>
        <div style="margin: 8px 0; display: flex; align-items: center; justify-content: space-between;">
            <div style="display: flex; align-items: center;">
                <i class="fa fa-map-marker" style="color: green; font-size: 14px; margin-right: 8px;"></i>
                <span>1-10 億元</span>
            </div>
            <span style="font-weight: bold; color: #388e3c;">{value_counts['1to10']}</span>
        </div>
        <div style="margin: 8px 0; display: flex; align-items: center; justify-content: space-between;">
            <div style="display: flex; align-items: center;">
                <i class="fa fa-map-marker" style="color: lightgray; font-size: 14px; margin-right: 8px;"></i>
                <span>未滿 1 億元</span>
            </div>
            <span style="font-weight: bold; color: #999;">{value_counts['under1']}</span>
        </div>
        <div style="margin-top: 12px; padding-top: 10px; border-top: 1px solid #ddd; font-size: 11px; color: #666;">
            <div><b>總標的數:</b> {len(valid_data)} 個</div>
            <div style="margin-top: 5px; color: #f57c00;">⚠️ Demo 資料，僅供展示</div>
        </div>
    </div>
    '''
    m.get_root().html.add_child(folium.Element(legend_html))

    # 儲存地圖
    m.save(str(output_path))
    print(f"  [OK] {output_path.name}")
    print(f"      - 超過100億: {value_counts['over100']} 個")
    print(f"      - 50-100億: {value_counts['50to100']} 個")
    print(f"      - 10-50億: {value_counts['10to50']} 個")
    print(f"      - 1-10億: {value_counts['1to10']} 個")
    print(f"      - 未滿1億: {value_counts['under1']} 個")


def main():
    print("載入 Mock 資料...")
    data = load_mock_data()
    print(f"載入 {len(data)} 筆資料")

    # 輸出目錄
    output_dir = Path(__file__).parent / 'visualization'
    output_dir.mkdir(exist_ok=True)

    print("\n生成地圖...")
    generate_map(data, output_dir / 'property_map.html')

    print("\n地圖生成完成！")


if __name__ == '__main__':
    main()
