"use client"

import React, { useEffect } from 'react';
import mapboxgl from 'mapbox-gl';

interface FaultLinesLayerProps {
    map: mapboxgl.Map | null;
    visible?: boolean;
}

export default function FaultLinesLayer({ map, visible = true }: FaultLinesLayerProps) {
    useEffect(() => {
        if (!map) return;

        // Function to add fault lines layer
        function addFaultLines() {
            const sourceId = 'indo_faults_lines';
            const layerId = 'indo_faults_line_layer';

            // Make sure map is defined
            if (!map) return;

            try {
                // Check if the source already exists
                if (!map.getSource(sourceId)) {
                    // Add fault lines data source
                    const url = "/geojson/indo_faults_lines.geojson";
                    map.addSource(sourceId, {
                        'type': 'geojson',
                        'generateId': true,
                        'data': url
                    });

                    // Add a line layer to visualize the fault lines
                    map.addLayer({
                        'id': layerId,
                        'type': 'line',
                        'source': sourceId,
                        'layout': {
                            'visibility': visible ? 'visible' : 'none'
                        },
                        'paint': {
                            'line-color': 'red',
                            'line-width': 1,
                            'line-opacity': 0.5
                        }
                    });
                } else if (map.getLayer(layerId)) {
                    // If the layer exists, just update its visibility
                    map.setLayoutProperty(
                        layerId,
                        'visibility',
                        visible ? 'visible' : 'none'
                    );
                }
            } catch (error) {
                console.warn("Error adding fault lines:", error);
            }
        }

        // Function to clean up layers
        function cleanupFaultLines() {
            try {
                if (!map || !map.getStyle()) return;

                const layerId = 'indo_faults_line_layer';
                const sourceId = 'indo_faults_lines';

                if (map.getLayer(layerId)) {
                    map.removeLayer(layerId);
                }

                if (map.getSource(sourceId)) {
                    map.removeSource(sourceId);
                }
            } catch (error) {
                console.warn("Error cleaning up fault lines:", error);
            }
        }

        let timeoutId: NodeJS.Timeout | undefined;

        // Try to add the layers now or set up listeners for when map is ready
        try {
            if (map.loaded() && map.isStyleLoaded()) {
                addFaultLines();
            } else {
                // Use multiple events to catch map ready state
                map.on('load', addFaultLines);
                map.on('style.load', addFaultLines);
                map.on('styledata', addFaultLines);

                // Fallback timeout
                timeoutId = setTimeout(() => {
                    addFaultLines();
                }, 2000);
            }
        } catch (error) {
            console.warn("Error setting up fault lines:", error);
        }

        // Single cleanup function
        return () => {
            if (timeoutId) clearTimeout(timeoutId);

            if (map) {
                map.off('load', addFaultLines);
                map.off('style.load', addFaultLines);
                map.off('styledata', addFaultLines);
            }

            cleanupFaultLines();
        };
    }, [map, visible]);

    return null;
}
