'use client'

import type { ComponentType } from 'react'

import type { GDSComponentProps } from '@graphprotocol/gds-css'

import { useControlled, useGDS } from '../hooks/index.ts'
import { cn } from '../utils/index.ts'
import { Button, type ButtonProps } from './Button.tsx'
import type { ToggleButtonMeta } from './ToggleButton.meta.ts'

const InternalButton = Button as ComponentType<
  ButtonProps.ButtonProps | ButtonProps.ToggleButtonProps | ButtonProps.LinkProps
>

export interface ToggleButtonProps
  extends
    Omit<ButtonProps.ToggleButtonProps, 'onChange' | 'variant'>,
    GDSComponentProps<typeof ToggleButtonMeta> {
  onChange?: ((checked: boolean) => void) | undefined
}

export function ToggleButton({
  checked: controlledChecked,
  defaultChecked,
  onChange,
  onClick,
  className,
  ...props
}: ToggleButtonProps) {
  useGDS()

  const [checked, setChecked] = useControlled(controlledChecked, defaultChecked ?? false, onChange)

  return (
    <InternalButton
      checked={checked}
      onClick={(event) => {
        setChecked(!checked)
        onClick?.(event)
      }}
      className={cn('gds-toggle-button', className)}
      {...props}
    />
  )
}
