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";
export function TerritoryFields({
initial = [],
onChange,
endpoint = "/api/v1/investment/territory-options",
}: {
initial?: TerritoryOption[];
onChange?: (path: TerritoryOption[]) => void;
endpoint?: string;
}) {
const [path, setPath] = useState(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 [q, setQ] = useState("");
const [page, setPage] = useState(1);
const [options, setOptions] = 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("");
}}
/>
))}
{message && {message}
}
);
}