import type { ButtonProps } from '@planview/pv-uikit'
import { ButtonEmpty } from '@planview/pv-uikit'
import { sizePx } from '@planview/pv-utilities'
import React from 'react'
import styled from 'styled-components'

const FluidButton = styled(ButtonEmpty)`
    width: 100%;
    height: 100%;
    align-items: center;
    min-height: ${sizePx.small};
    text-align: left;

    &:focus-visible {
        outline: none;
    }
`

export type GridCellButtonProps = Omit<
    ButtonProps,
    'children' | 'tabIndex' | 'withCaret' | 'size'
> & {
    /**
     * Visible label.
     *
     * If no tooltip is provided and the visible label is truncated, a tooltip will automatically be applied showing the label on hover/focus
     */
    label?: string
    /**
     * Accessible tab index. You should generally pass through the tabIndex
     * provided to the Renderer component.
     */
    tabIndex: number
}

const GridCellButtonImpl = ({ label = '', ...rest }: GridCellButtonProps) => (
    <FluidButton
        {...rest}
        onClick={(e) => {
            //Prevent row being selected
            e.stopPropagation()
            rest.onClick?.(e)
        }}
    >
        {label}
    </FluidButton>
)
/**
 *
 * `import { GridCellButton } from '@planview/pv-grid'`
 *
 * The [GridCellButton](https://design.planview.com/components/grid/grid-renderer-button) is best suited for triggering actions within a grid, such as deleting a row or opening a modal.
 *
 * The component renders an `ButtonEmpty` with fluid height and width with a built-in tooltip.
 *
 * ### Responsiveness
 * The`GridCellButton` will apply a tooltip whenever the text is truncated. This behavior can be overridden by providing the `tooltip` prop
 *
 * ### Accessibility
 * When using the `GridCellButton` component in your Renderer function, it is important to set `focusStrategy` to `"inline"`.
 * This will make sure focus is applied on the button inside the grid-cell on keyboard navigation which is important for screen readers to be able to read out the
 * navigation state correctly.
 *
 * ```tsx
 * const deleteColumn: Column<Team> = {
 *      id: 'delete',
 *      label: '',
 *      resizable: false,
 *      width: size.small,
 *      cell: {
 *          focusStrategy: 'inline',
 *          Renderer({ rowId, tabIndex }) {
 *              return (
 *                  <GridCellButton
 *                      tooltip={'Delete team'}
 *                      tabIndex={tabIndex}
 *                      icon={<Trash />}
 *                      onClick={() =>
 *                          //some action here
 *                      }
 *                  />
 *              )
 *          },
 *      },
 *  },
 * ```
 */
export const GridCellButton = React.memo(
    GridCellButtonImpl
) as typeof GridCellButtonImpl
