import { Plus } from "lucide-react";
import { useNavigate } from "@tanstack/react-router";
import { businessLabel, useBusiness } from "@/lib/business-context";

function initials(name: string) {
  return name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0]?.toUpperCase())
    .join("");
}

export function AccountBusinessRail({ onAdd }: { onAdd?: () => void }) {
  const { businesses, active, setActiveId, isLoading } = useBusiness();
  const navigate = useNavigate();

  function choose(id: string) {
    setActiveId(id);
    navigate({ to: "/partner/dashboard" });
  }

  return (
    <div className="flex h-full w-full flex-col items-center border-r border-hairline bg-white py-4">
      <div className="flex w-full flex-1 flex-col items-center gap-3 overflow-y-auto px-3">
        {isLoading && (
          <span className="inline-flex h-10 w-10 animate-pulse rounded-full bg-ink-3/10" />
        )}
        {businesses.map((b) => {
          const selected = active?.id === b.id;
          return (
            <button
              key={b.id}
              type="button"
              onClick={() => choose(b.id)}
              title={businessLabel(b)}
              className={`relative inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-bold transition-colors ${
                selected
                  ? "bg-[#0a0a12] text-white"
                  : "bg-ink-3/10 text-ink-2 hover:bg-ink-3/15 hover:text-ink"
              }`}
            >
              {initials(businessLabel(b))}
            </button>
          );
        })}
        {onAdd && (
          <button
            type="button"
            onClick={onAdd}
            title="Add new business"
            className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-dashed border-ink-3 text-ink-3 transition-colors hover:border-ink hover:text-ink"
          >
            <Plus className="h-5 w-5" />
          </button>
        )}
      </div>
    </div>
  );
}
