import { useEffect, useMemo, useState } from "react"; import { toast } from "sonner"; import { OrganisationForm } from "@/components/organisation-form"; import { useSelection } from "@/components/selection-provider"; import { Button } from "@/components/ui/button"; import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { useOrganisations } from "@/lib/query/hooks"; import { cn } from "@/lib/utils"; import OrgIcon from "./org-icon"; export function OrganisationSelect({ placeholder = "Select Organisation", contentClass, showLabel = false, label = "Organisation", labelPosition = "top", triggerClassName, noDecoration, trigger, }: { placeholder?: string; contentClass?: string; showLabel?: boolean; label?: string; labelPosition?: "top" | "bottom"; triggerClassName?: string; noDecoration?: boolean; trigger?: React.ReactNode; }) { const [open, setOpen] = useState(false); const [pendingOrganisationId, setPendingOrganisationId] = useState(null); const { data: organisationsData = [] } = useOrganisations(); const { selectedOrganisationId, selectOrganisation } = useSelection(); const organisations = useMemo( () => [...organisationsData].sort((a, b) => a.Organisation.name.localeCompare(b.Organisation.name)), [organisationsData], ); const selectedOrganisation = useMemo( () => organisations.find((org) => org.Organisation.id === selectedOrganisationId) ?? null, [organisations, selectedOrganisationId], ); useEffect(() => { if (!pendingOrganisationId) return; const organisation = organisations.find((org) => org.Organisation.id === pendingOrganisationId); if (organisation) { selectOrganisation(organisation); setPendingOrganisationId(null); } }, [organisations, pendingOrganisationId, selectOrganisation]); return ( ); }