import { type ReactElement } from "react"
import * as React from "react"
import { type VariantProps } from "class-variance-authority"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { Toggle as ToggleComponent } from "@base-ui/react/toggle"
import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle"

const ToggleGroupContext = React.createContext<
  VariantProps<typeof toggleVariants> & {
    spacing?: number
  }
>({
  size: "default",
  variant: "default",
  spacing: 0,
})

export type ToggleGroupProps = React.ComponentProps<typeof ToggleGroupPrimitive> &
  VariantProps<typeof toggleVariants> & {
    spacing?: number
    /** shadcn-compatible alias: "single" -- multiple=false, "multiple" -- multiple=true */
    type?: "single" | "multiple"
  }

function ToggleGroup({
  className,
  variant,
  size,
  spacing = 0,
  type,
  children,
  ...props
}: ToggleGroupProps): ReactElement {
  return (
    <ToggleGroupPrimitive
      className={cn(
        // WealthX: removed rounded-md (sharp corners) and shadow-xs (flat panels)
        "group/toggle-group flex w-fit items-center gap-[--spacing(var(--gap))]",
        className
      )}
      data-size={size}
      data-slot="toggle-group"
      data-spacing={spacing}
      data-variant={variant}
      multiple={type === "multiple"}
      style={{ "--gap": spacing } as React.CSSProperties}
      {...props}
    >
      <ToggleGroupContext.Provider value={{ variant, size, spacing }}>
        {children}
      </ToggleGroupContext.Provider>
    </ToggleGroupPrimitive>
  )
}

export type ToggleGroupItemProps = React.ComponentProps<typeof ToggleComponent> &
  VariantProps<typeof toggleVariants>

function ToggleGroupItem({
  className,
  children,
  variant,
  size,
  ...props
}: ToggleGroupItemProps): ReactElement {
  const context = React.useContext(ToggleGroupContext)

  return (
    <ToggleComponent
      className={cn(
        toggleVariants({
          variant: context.variant || variant,
          size: context.size || size,
        }),
        "w-auto min-w-0 shrink-0 focus:z-10 focus-visible:z-10",
        // WealthX: no rounded corners on grouped items
        "data-[spacing=0]:rounded-none data-[spacing=0]:shadow-none data-[spacing=0]:data-[variant=outline]:border-l-0 data-[spacing=0]:data-[variant=outline]:first:border-l",
        className
      )}
      data-size={context.size || size}
      data-slot="toggle-group-item"
      data-spacing={context.spacing}
      data-variant={context.variant || variant}
      {...props}
    >
      {children}
    </ToggleComponent>
  )
}

export { ToggleGroup, ToggleGroupItem }
