import { useEffect, useId, useState } from "react"; import { api } from "@/pages/investment/shared"; export type TerritoryOption = { id: string; name: string; parent_id: string | null; location_type: string; deleted_at?: string | null; source_code?: string | null; }; type Option = TerritoryOption; const levels = ["province", "district", "admin_post", "locality"]; const labels = ["Província", "Distrito", "Posto administrativo", "Localidade"]; const control = "w-full rounded border bg-background p-2 text-foreground"; const emptyTerritoryPath: TerritoryOption[] = []; export function ProvinceSelect({ value, onChange, endpoint = "/api/v1/investment/territory-options", placeholder = "Seleccione uma província", className = control, label = "Província", required = false, }: { value: string; onChange: (value: string) => void; endpoint?: string; placeholder?: string; className?: string; label?: string; required?: boolean; }) { const id = useId(); const [options, setOptions] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [retry, setRetry] = useState(0); useEffect(() => { const controller = new AbortController(); setLoading(true); setError(""); fetch(`${endpoint}?type=province&page=1`, { signal: controller.signal, headers: { Accept: "application/json" }, }) .then(async (response) => { if (!response.ok) throw new Error("Não foi possível carregar as províncias."); return response.json(); }) .then((data) => setOptions(data.data)) .catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "Erro de ligação."); }) .finally(() => { if (!controller.signal.aborted) setLoading(false); }); return () => controller.abort(); }, [endpoint, retry]); return ( <> option.name === value) ? value : ""} disabled={loading || Boolean(error)} onChange={(event) => onChange(event.target.value)} > {loading ? "A carregar províncias…" : placeholder} {options.map((option) => ( {option.name} ))} {error && ( {error}{" "} setRetry((current) => current + 1)}> Tentar novamente )} > ); } export function TerritoryFields({ initial = emptyTerritoryPath, onChange, endpoint = "/api/v1/investment/territory-options", }: { initial?: TerritoryOption[]; onChange?: (path: TerritoryOption[]) => void; endpoint?: string; }) { const [path, setPath] = useState(initial); useEffect(() => setPath(initial), [initial]); return ( {(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map( (field, index) => ( { const next = [...path.slice(0, index), ...(value ? [value] : [])]; setPath(next); onChange?.(next); }} /> ), )} ); } export function TerritoryLevel({ index, parent, selected, onChange, endpoint = "/management/territory-options", fieldError, }: { index: number; parent: string; selected?: Option; onChange: (value?: Option) => void; endpoint?: string; fieldError?: string; }) { const id = useId(); const [page, setPage] = useState(1); const [options, setOptions] = useState([]); const [more, setMore] = useState(false); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const [retry, setRetry] = useState(0); const enabled = index === 0 || Boolean(parent); useEffect(() => { setOptions([]); setMore(false); if (!enabled) return; setLoading(true); const controller = new AbortController(); const timer = setTimeout(async () => { setLoading(true); setError(""); try { const params = new URLSearchParams({ type: levels[index], parent_id: parent, page: String(page), }); const response = await fetch(`${endpoint}?${params}`, { signal: controller.signal, headers: { Accept: "application/json" }, }); if (!response.ok) throw new Error("Não foi possível carregar as localizações."); const data = await response.json(); if (controller.signal.aborted) return; setOptions(data.data); setMore(Boolean(data.next_page_url)); } catch (e) { if (!controller.signal.aborted) setError(e instanceof Error ? e.message : "Erro de ligação."); } finally { if (!controller.signal.aborted) setLoading(false); } }, 250); return () => { clearTimeout(timer); controller.abort(); }; }, [index, parent, page, enabled, endpoint, retry]); return ( {labels[index]} onChange(options.find((o) => o.id === e.target.value))} > {enabled ? "Seleccione" : "Seleccione o nível anterior"} {selected && !options.some((o) => o.id === selected.id) && ( {selected.name} {selected.deleted_at ? " (arquivada)" : " (selecção actual)"} )} {options.map((o) => ( {o.name} {o.source_code ? ` (${o.source_code})` : ""} ))} {loading && A carregar…} {error && ( {error}{" "} setRetry(retry + 1)}> Tentar novamente )} {fieldError && ( {fieldError} )} {enabled && !loading && !error && options.length === 0 && ( Sem opções para esta pesquisa. )} {page > 1 && ( setPage(page - 1)}> Anterior )} {more && ( setPage(page + 1)}> Mais opções )} ); } export default function InvestmentTerritory({ kind, id }: { kind: string; id: string | number }) { const [path, setPath] = useState([]); const [version, setVersion] = useState(null); const [message, setMessage] = useState(""); const [busy, setBusy] = useState(false); useEffect(() => { let active = true; api(`/management/territories/${kind}/${id}`) .then((data) => { if (!active) return; setPath( levels.flatMap((level) => data.path.filter((o: Option) => o.location_type === level), ), ); setVersion(data.version); }) .catch((e) => { if (active) setMessage(e.message); }); return () => { active = false; }; }, [kind, id]); return ( Localização do investimento Seleccione até ao nível conhecido. Alterar um nível limpa as selecções seguintes. {levels.map((level, index) => ( { setPath([...path.slice(0, index), ...(value ? [value] : [])]); setMessage(""); }} /> ))} { setBusy(true); setMessage(""); try { const data = await api(`/management/territories/${kind}/${id}`, { version, path: path.map((o) => o.id), }); setVersion(data.version); setMessage("Localização associada e guardada."); } catch (e) { setMessage(e instanceof Error ? e.message : "Erro ao guardar."); } finally { setBusy(false); } }} > Guardar localização {message && {message}} ); }
A carregar…
{fieldError}
Sem opções para esta pesquisa.
Seleccione até ao nível conhecido. Alterar um nível limpa as selecções seguintes.
{message}