// src/components/org-switcher.tsx — switch the active organization (only shown
// when the user belongs to more than one). Persists the choice so the next login
// restores it (see auth.ts session hook + persistActiveOrgAction).
//
// Orgs + the active id are resolved server-side in the (app) layout and passed
// in as props. We deliberately do NOT use authClient.useListOrganizations()/
// useActiveOrganization() here: those Better Auth/nanostore hooks crash during
// the SSR pass ("Cannot read properties of null (reading 'useRef')") and would
// re-fetch RSC-provided data on the client (see the backlink nav-deadlock note).
"use client";

import { Building2Icon, CheckIcon, ChevronsUpDownIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/components/ui/sidebar";
import { authClient } from "@/lib/auth-client";
import { persistActiveOrgAction } from "@/lib/org/active-org-action";

export type OrgSummary = { id: string; name: string };

export function OrgSwitcher({
  orgs = [],
  activeOrgId = null,
}: {
  orgs?: OrgSummary[];
  activeOrgId?: string | null;
}) {
  const { isMobile } = useSidebar();
  const router = useRouter();
  const [switching, setSwitching] = useState(false);

  // Only relevant for multi-org members (a team member invited into another org).
  if (orgs.length <= 1) return null;

  const active = orgs.find((o) => o.id === activeOrgId) ?? null;

  async function switchTo(orgId: string) {
    if (orgId === activeOrgId || switching) return;
    setSwitching(true);
    try {
      await authClient.organization.setActive({ organizationId: orgId });
      await persistActiveOrgAction(orgId);
      router.refresh();
    } finally {
      setSwitching(false);
    }
  }

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton
              size="lg"
              className="data-[state=open]:bg-sidebar-accent"
            >
              <div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
                <Building2Icon className="size-4" />
              </div>
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-medium">
                  {active?.name ?? "Organisation"}
                </span>
                <span className="truncate text-muted-foreground text-xs">
                  Organisation
                </span>
              </div>
              <ChevronsUpDownIcon className="ml-auto size-4" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
            align="start"
            side={isMobile ? "bottom" : "right"}
          >
            <DropdownMenuLabel className="text-muted-foreground text-xs">
              Organisations
            </DropdownMenuLabel>
            {orgs.map((o) => (
              <DropdownMenuItem
                key={o.id}
                onClick={() => switchTo(o.id)}
                disabled={switching}
                className="gap-2"
              >
                <span className="min-w-0 truncate">{o.name}</span>
                {o.id === active?.id ? (
                  <CheckIcon className="ml-auto size-4" />
                ) : null}
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  );
}
