import { router, usePage } from '@inertiajs/react';
import { ChevronRight } from 'lucide-react';

type Org = { id: number; name: string };

// Sits at the top of the sidebar (the "Salonsbyjc >" control in the reference).
export function OrganizationSwitcher() {
  const { current, memberships } = usePage().props.organization as {
    current: Org | null;
    memberships: Org[];
  };

  function switchTo(id: number) {
    router.post('/organizations/switch', { organization_id: id }, { preserveScroll: true });
  }

  return (
    <div className="rounded-lg border border-border p-1">
      <button
        className="flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-sm font-medium hover:bg-muted"
        onClick={() => {
          // Open a menu of memberships; single-org users just see their org.
          if (memberships.length > 1) {
            const next = memberships.find((o) => o.id !== current?.id);
            if (next) switchTo(next.id);
          }
        }}
      >
        <span className="truncate">{current?.name ?? 'Select organization'}</span>
        <ChevronRight className="size-4 text-muted-foreground" />
      </button>
    </div>
  );
}
