import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Dimensions,
  TouchableOpacity,
  Alert,
} from 'react-native';
import { WebView } from 'react-native-webview';
import Icon from 'react-native-vector-icons/Ionicons';
import { apiService } from '../services/apiService';

const { width, height } = Dimensions.get('window');

export default function MapScreen() {
  const [properties, setProperties] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshKey, setRefreshKey] = useState(0);

  useEffect(() => {
    loadMapData();
  }, []);

  const loadMapData = async () => {
    try {
      setLoading(true);
      const data = await apiService.getPropertiesForMap();
      setProperties(data);
    } catch (error) {
      console.error('Failed to load map data:', error);
      Alert.alert('Error', 'Failed to load map data');
    } finally {
      setLoading(false);
    }
  };

  const handleRefresh = () => {
    setRefreshKey(prev => prev + 1);
    loadMapData();
  };

  // Generate map HTML with markers
  const generateMapHTML = () => {
    const markers = properties.map(property => ({
      id: property.id,
      lat: parseFloat(property.latitude || '2.0469'),
      lng: parseFloat(property.longitude || '45.3182'),
      title: property.title,
      price: property.price,
      type: property.type,
      image: property.image_url
    })).filter(marker => !isNaN(marker.lat) && !isNaN(marker.lng));

    return `
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            body { 
                margin: 0; 
                padding: 0; 
                font-family: Arial, sans-serif; 
            }
            #map { 
                height: 100vh; 
                width: 100vw; 
            }
            .info-window {
                max-width: 200px;
                font-size: 12px;
            }
            .property-title {
                font-weight: bold;
                color: #004F9B;
                margin-bottom: 5px;
            }
            .property-price {
                color: #0091B9;
                font-weight: bold;
                font-size: 14px;
                margin-bottom: 5px;
            }
            .property-type {
                background: ${properties[0]?.type === 'buy' ? '#0091B9' : '#FF6500'};
                color: white;
                padding: 2px 6px;
                border-radius: 3px;
                font-size: 10px;
                display: inline-block;
            }
            .stats-overlay {
                position: absolute;
                top: 10px;
                left: 10px;
                background: rgba(0, 79, 155, 0.9);
                color: white;
                padding: 8px 12px;
                border-radius: 6px;
                font-size: 12px;
                z-index: 1000;
            }
        </style>
    </head>
    <body>
        <div class="stats-overlay">
            📍 ${properties.length} Properties | 🗺️ Live Mogadishu Map
        </div>
        <iframe 
            src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d127406.93705195957!2d45.31824871875!3d2.046934!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3d58424c6fc73c2d%3A0x9c9b6a8c2f8b4a5c!2sMogadishu%2C%20Somalia!5e1!3m2!1sen!2s!4v${Date.now()}" 
            width="100%" 
            height="100%" 
            style="border:0;" 
            allowfullscreen="" 
            loading="lazy" 
            referrerpolicy="no-referrer-when-downgrade">
        </iframe>
        
        <script>
            // Add property markers overlay (simulated)
            window.addEventListener('load', function() {
                setTimeout(() => {
                    const markers = document.createElement('div');
                    markers.style.position = 'absolute';
                    markers.style.top = '0';
                    markers.style.left = '0';
                    markers.style.width = '100%';
                    markers.style.height = '100%';
                    markers.style.pointerEvents = 'none';
                    markers.style.zIndex = '999';
                    
                    ${markers.map((marker, index) => `
                        const marker${index} = document.createElement('div');
                        marker${index}.style.position = 'absolute';
                        marker${index}.style.left = '${20 + (index % 10) * 30}px';
                        marker${index}.style.top = '${100 + Math.floor(index / 10) * 40}px';
                        marker${index}.style.width = '12px';
                        marker${index}.style.height = '12px';
                        marker${index}.style.backgroundColor = '${marker.type === 'buy' ? '#dc2626' : '#2563eb'}';
                        marker${index}.style.borderRadius = '50%';
                        marker${index}.style.border = '2px solid white';
                        marker${index}.style.boxShadow = '0 2px 4px rgba(0,0,0,0.3)';
                        marker${index}.style.pointerEvents = 'all';
                        marker${index}.style.cursor = 'pointer';
                        marker${index}.title = '${marker.title} - $${marker.price}';
                        markers.appendChild(marker${index});
                    `).join('')}
                    
                    document.body.appendChild(markers);
                }, 2000);
            });
        </script>
    </body>
    </html>
    `;
  };

  return (
    <View style={styles.container}>
      {/* Map Controls */}
      <View style={styles.controls}>
        <TouchableOpacity style={styles.refreshButton} onPress={handleRefresh}>
          <Icon name="refresh" size={20} color="#fff" />
          <Text style={styles.refreshText}>Refresh</Text>
        </TouchableOpacity>
        
        <View style={styles.legend}>
          <View style={styles.legendItem}>
            <View style={[styles.legendDot, { backgroundColor: '#dc2626' }]} />
            <Text style={styles.legendText}>For Sale</Text>
          </View>
          <View style={styles.legendItem}>
            <View style={[styles.legendDot, { backgroundColor: '#2563eb' }]} />
            <Text style={styles.legendText}>For Rent</Text>
          </View>
        </View>
      </View>

      {/* Map */}
      <View style={styles.mapContainer}>
        {!loading ? (
          <WebView
            key={refreshKey}
            source={{ html: generateMapHTML() }}
            style={styles.webView}
            onError={(syntheticEvent) => {
              const { nativeEvent } = syntheticEvent;
              console.error('WebView error:', nativeEvent);
            }}
            javaScriptEnabled={true}
            domStorageEnabled={true}
            startInLoadingState={true}
            renderLoading={() => (
              <View style={styles.loadingOverlay}>
                <Icon name="map" size={50} color="#0091B9" />
                <Text style={styles.loadingText}>Loading Mogadishu Map...</Text>
              </View>
            )}
          />
        ) : (
          <View style={styles.loadingOverlay}>
            <Icon name="map" size={50} color="#0091B9" />
            <Text style={styles.loadingText}>Loading Map Data...</Text>
          </View>
        )}
      </View>

      {/* Map Info */}
      <View style={styles.mapInfo}>
        <View style={styles.infoCard}>
          <View style={styles.infoRow}>
            <Icon name="location" size={16} color="#0091B9" />
            <Text style={styles.infoText}>Mogadishu, Somalia</Text>
          </View>
          <View style={styles.infoRow}>
            <Icon name="business" size={16} color="#0091B9" />
            <Text style={styles.infoText}>{properties.length} Properties Available</Text>
          </View>
          <View style={styles.infoRow}>
            <Icon name="time" size={16} color="#0091B9" />
            <Text style={styles.infoText}>Updated Live</Text>
          </View>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  controls: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 15,
    paddingVertical: 10,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  refreshButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#0091B9',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 6,
    gap: 6,
  },
  refreshText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '600',
  },
  legend: {
    flexDirection: 'row',
    gap: 15,
  },
  legendItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
  },
  legendDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
    borderWidth: 2,
    borderColor: '#fff',
  },
  legendText: {
    fontSize: 12,
    color: '#666',
    fontWeight: '500',
  },
  mapContainer: {
    flex: 1,
    position: 'relative',
  },
  webView: {
    flex: 1,
  },
  loadingOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: '#f8f9fa',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 15,
  },
  loadingText: {
    fontSize: 16,
    color: '#004F9B',
    fontWeight: '500',
  },
  mapInfo: {
    backgroundColor: '#fff',
    paddingHorizontal: 15,
    paddingVertical: 10,
    borderTopWidth: 1,
    borderTopColor: '#e0e0e0',
  },
  infoCard: {
    gap: 8,
  },
  infoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  infoText: {
    fontSize: 14,
    color: '#666',
    fontWeight: '500',
  },
});