"use client";

import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useTransition } from "react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { switchActiveOrganization } from "@/lib/actions/organization";

function roleLabel(role: "owner" | "admin" | "member", t: ReturnType<typeof useTranslations>) {
  switch (role) {
    case "owner":
      return t("roleOwner");
    case "admin":
      return t("roleAdmin");
    case "member":
      return t("roleMember");
  }
}

export function ExistingOrgsList({
  organizations,
}: {
  organizations: { id: string; name: string; role: "owner" | "admin" | "member" }[];
}) {
  const t = useTranslations("Onboarding");
  const tSwitcher = useTranslations("Org.switcher");
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  function handleSwitch(orgId: string) {
    startTransition(async () => {
      try {
        await switchActiveOrganization({ organizationId: orgId });
        router.push("/dashboard");
      } catch {
        toast.error(tSwitcher("switchFailed"));
      }
    });
  }

  return (
    <ul className="flex flex-col gap-2">
      {organizations.map((org) => (
        <li key={org.id} className="flex items-center justify-between rounded-md border px-3 py-2">
          <span className="flex items-center gap-2">
            <span className="font-medium">{org.name}</span>
            <span className="text-xs tracking-wider text-muted-foreground uppercase">
              {roleLabel(org.role, tSwitcher)}
            </span>
          </span>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            disabled={isPending}
            onClick={() => handleSwitch(org.id)}
          >
            {t("existingSwitchLabel")}
          </Button>
        </li>
      ))}
    </ul>
  );
}
