import { useEffect, useState } from 'react' import { datasetsApi } from '../services/api' import { formatError } from '../lib/formatError' import type { DatasetCreateResponse, VectorSelectionBBox, VectorSelectionResponse } from '../types' interface MapSelectionExtractOptions { selectedProjectId: string | null selectedDataset: DatasetCreateResponse | null isVectorDatasetType: (datasetType: string) => boolean } export function useMapSelectionExtract({ selectedProjectId, selectedDataset, isVectorDatasetType, }: MapSelectionExtractOptions) { const [mapSelectionBbox, setMapSelectionBbox] = useState(null) const [mapSelectionResult, setMapSelectionResult] = useState(null) const [mapSelectionLoading, setMapSelectionLoading] = useState(false) const [mapSelectionError, setMapSelectionError] = useState(null) useEffect(() => { setMapSelectionBbox(null) setMapSelectionResult(null) setMapSelectionError(null) }, [selectedProjectId, selectedDataset?.id]) const runMapSelectionExtract = async (bbox: VectorSelectionBBox) => { if (!selectedProjectId || !selectedDataset) { setMapSelectionError('Open a vector dataset before extracting a map area.') return null } if (!isVectorDatasetType(selectedDataset.dataset_type)) { setMapSelectionError('Area extraction requires an active vector dataset.') return null } setMapSelectionLoading(true) setMapSelectionError(null) setMapSelectionBbox(bbox) try { const response = await datasetsApi.selectVectorFeatures(selectedProjectId, selectedDataset.id, { bbox: { ...bbox, crs: 'EPSG:4326' }, limit: 250, }) setMapSelectionResult(response) return response } catch (error) { setMapSelectionResult(null) setMapSelectionError(formatError(error, 'Area extraction failed')) return null } finally { setMapSelectionLoading(false) } } const resetMapSelectionExtract = () => { setMapSelectionBbox(null) setMapSelectionResult(null) setMapSelectionError(null) } return { mapSelectionBbox, mapSelectionResult, mapSelectionLoading, mapSelectionError, runMapSelectionExtract, resetMapSelectionExtract, setMapSelectionBbox, } }