import React from 'react'
import { ToolbarItem, ToolbarItemView } from '../wrapper'
import { Tooltip } from '@planview/pv-uikit'
import { LogoContainer, StrippedAnchor } from '../navigation-bar/styles'
import { useIsFocusVisible } from '@planview/pv-utilities'
import { useMergeRefs } from '../utils/refs'
import styled from 'styled-components'

export type MainNavigationLogoProps = {
    /**
     * url to navigate to when clicking on the logotype. Using this prop will wrap the logo in an <a> -element
     */
    url?: string
    /**
     * descriptive label
     */
    label?: string
} & React.HTMLAttributes<HTMLElement>

const StyledLogo = styled.svg`
    height: 31px;
`
export function asProductLogo(Logo: React.ElementType) {
    const Component: React.FC<MainNavigationLogoProps> = ({
        url,
        label,
        ...rest
    }) => {
        const {
            innerRef: _innerRef,
            focusVisible,
            ...focusProps
        } = useIsFocusVisible()
        const anchorRef = React.useRef<HTMLAnchorElement>(null)
        const mergedRef = useMergeRefs([anchorRef, focusProps.ref])
        return url !== undefined ? (
            <ToolbarItem>
                <ToolbarItemView<HTMLAnchorElement> refOverride={anchorRef}>
                    {(
                        ref,
                        {
                            toolbarItemProps: {
                                focused: _focused,
                                ...toolbarItemProps
                            },
                        }
                    ) => (
                        <Tooltip unwrapped text={label} show={!!label}>
                            <StrippedAnchor
                                {...rest}
                                {...toolbarItemProps}
                                {...focusProps}
                                $focusVisible={focusVisible}
                                onClick={(ev) => {
                                    toolbarItemProps.onClick(ev)
                                    rest.onClick?.(ev)
                                }}
                                onKeyDown={(ev) => {
                                    toolbarItemProps.onKeyDown(ev)
                                    rest.onKeyDown?.(ev)
                                }}
                                ref={mergedRef}
                                href={url}
                                aria-label={label}
                            >
                                <StyledLogo as={Logo} />
                            </StrippedAnchor>
                        </Tooltip>
                    )}
                </ToolbarItemView>
            </ToolbarItem>
        ) : (
            <LogoContainer {...rest} role="img" aria-label={label}>
                <StyledLogo as={Logo} />
            </LogoContainer>
        )
    }
    return Component
}
