import type { FeatureCollection, Geometry } from 'geojson';
import { useEffect, useState } from 'react';
import { MapGeoJSON } from '@/components/ui/map';
import { CAPAS, fetchFeatureCollection, NEXTGIS_URL } from '../lib/nextgis';
import type { PredioProperties, SeleccionPredio } from '../types';

type CapaBaseProps = {
    onSelect: (seleccion: SeleccionPredio) => void;
};

export function CapaBase({ onSelect }: CapaBaseProps) {
    const [geojson, setGeojson] = useState<FeatureCollection<
        Geometry,
        PredioProperties
    > | null>(null);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        fetchFeatureCollection(NEXTGIS_URL)
            .then(setGeojson)
            .catch((fetchError) => {
                setError(
                    fetchError instanceof Error
                        ? fetchError.message
                        : 'Error al cargar predios',
                );
            });
    }, []);

    if (error) {
        return (
            <div className="absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-destructive">
                {error}
            </div>
        );
    }

    if (!geojson) {
        return null;
    }

    return (
        <MapGeoJSON<PredioProperties>
            id={CAPAS.base.id}
            data={geojson}
            interactive
            promoteId="fid"
            fillPaint={{
                'fill-color': '#f59e0b',
                'fill-opacity': 0.15,
            }}
            fillHoverPaint={{
                'fill-opacity': 0.35,
            }}
            linePaint={{
                'line-color': '#d97706',
                'line-width': 0.75,
            }}
            onClick={(event) =>
                onSelect({
                    properties: event.feature.properties,
                    lng: event.longitude,
                    lat: event.latitude,
                })
            }
        />
    );
}
