import { Building2, X } from "lucide-react"; import type { ReactNode } from "react"; import { useEffect, useState } from "react"; import { Button } from "../../../components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from "../../../components/ui/dialog"; import { Label } from "../../../components/ui/label"; import type { TenantSummary } from "../../../lib/adminApi"; import { t } from "../../../lib/i18n"; import { buildAuthenticatedOrgChartTenantPickerUrl, parseOrgChartTenantSelection, } from "../../users/orgChartPicker"; import { filterParentTenants } from "./ParentTenantSelector.helpers"; type ParentTenantSelectorProps = { id: string; label: string; value: string; onChange: (value: string) => void; tenants: TenantSummary[]; noneLabel: string; helpText?: string; excludeTenantId?: string; labelAction?: ReactNode; contextLabel?: string; orgChartPickerLabel?: string; orgChartTenantId?: string; localPickerLabel?: string; localTenantFilter?: (tenant: TenantSummary) => boolean; compact?: boolean; controlTestId?: string; disabled?: boolean; }; export function ParentTenantSelector({ id, label, value, onChange, tenants, noneLabel, helpText, excludeTenantId, labelAction, contextLabel, orgChartPickerLabel, orgChartTenantId, localPickerLabel, localTenantFilter, compact = false, controlTestId, disabled = false, }: ParentTenantSelectorProps) { const [pickerOpen, setPickerOpen] = useState(false); const [localPickerOpen, setLocalPickerOpen] = useState(false); const [localSearch, setLocalSearch] = useState(""); const selectedTenant = tenants.find((tenant) => tenant.id === value); const localCandidates = filterParentTenants( localTenantFilter ? tenants.filter(localTenantFilter) : tenants, localSearch, false, excludeTenantId, ); const pickerUrl = buildAuthenticatedOrgChartTenantPickerUrl( import.meta.env.ORGFRONT_URL, { tenantId: orgChartTenantId, }, ); useEffect(() => { if (!pickerOpen) return; const onMessage = (event: MessageEvent) => { const selection = parseOrgChartTenantSelection(event.data); if (!selection) return; if (excludeTenantId && selection.id === excludeTenantId) return; onChange(selection.id); setPickerOpen(false); }; window.addEventListener("message", onMessage); return () => window.removeEventListener("message", onMessage); }, [excludeTenantId, onChange, pickerOpen]); return (
{helpText}
)}