import { useState } from 'react' import type { DatasetCreateResponse, VectorSelectionBBox } from '../types' import { formatError } from '../lib/formatError' import { datasetsApi } from '../services/api' interface UseMapSelectionDatasetOptions { selectedProjectId: string | null selectedDataset: DatasetCreateResponse | null isVectorDatasetType: (datasetType: string) => boolean loadProjectData: (projectId: string) => Promise loadDatasetDetails: (projectId: string, dataset: DatasetCreateResponse) => Promise setMapLayerVisible: (visible: boolean) => void } export function useMapSelectionDataset({ selectedProjectId, selectedDataset, isVectorDatasetType, loadProjectData, loadDatasetDetails, setMapLayerVisible, }: UseMapSelectionDatasetOptions) { const [selectionDatasetSaving, setSelectionDatasetSaving] = useState(false) const [selectionDatasetError, setSelectionDatasetError] = useState(null) const [latestSelectionDataset, setLatestSelectionDataset] = useState(null) const deriveMapSelectionDataset = async (bbox: VectorSelectionBBox, areaId?: string) => { if (!selectedProjectId || !selectedDataset || !isVectorDatasetType(selectedDataset.dataset_type)) { setSelectionDatasetError('Kies eerst een vectorbron om het gebied als bron te bewaren.') return null } setSelectionDatasetSaving(true) setSelectionDatasetError(null) try { const derived = await datasetsApi.deriveVectorSelection(selectedProjectId, selectedDataset.id, { bbox: { ...bbox, crs: 'EPSG:4326' }, area_id: areaId, limit: 250, output_name: `${selectedDataset.name.replace(/\.(geo)?json$/i, '')}-selection-dataset`, }) setLatestSelectionDataset(derived) await loadProjectData(selectedProjectId) await loadDatasetDetails(selectedProjectId, derived) setMapLayerVisible(true) return derived } catch (error) { setSelectionDatasetError(formatError(error, 'Het gebied kon niet als bron worden bewaard')) return null } finally { setSelectionDatasetSaving(false) } } return { selectionDatasetSaving, selectionDatasetError, latestSelectionDataset, deriveMapSelectionDataset, } }