import React, { useMemo } from 'react'
import withDefaults from '../utils/with-defaults'
import useTheme from '../use-theme'
import TreeLeafIcon from './tree-leaf-icon'
import { useTreeContext } from './tree-context'
import TreeIndents from './tree-indents'
import { makeLeafPath, stopPropagation } from './tree-help'

interface Props {
  name: string
  extra?: string
  parentPath?: string
  level?: number
  className?: string
}

const defaultProps = {
  level: 0,
  className: '',
  parentPath: ''
}

type NativeAttrs = Omit<React.HTMLAttributes<any>, keyof Props>
export type TreeLeafProps = Props & typeof defaultProps & NativeAttrs

const TreeLeaf: React.FC<React.PropsWithChildren<TreeLeafProps>> = ({
  name,
  parentPath,
  level,
  extra,
  className,
  ...props
}) => {
  const theme = useTheme()
  const { onLeafClick } = useTreeContext()
  const currentPath = useMemo(() => makeLeafPath(name, parentPath), [])
  const clickHandler = (event: React.MouseEvent) => {
    stopPropagation(event)
    onLeafClick && onLeafClick(currentPath)
  }

  return (
    <div className={`leaf ${className}`} onClick={clickHandler} {...props}>
      <div className="names">
        <TreeIndents count={level} />
        <span className="icon">
          <TreeLeafIcon />
        </span>
        <span className="name">
          {name}
          {extra && <span className="extra">{extra}</span>}
        </span>
      </div>
      <style jsx>{`
        .leaf {
          cursor: pointer;
          line-height: 1;
          user-select: none;
          margin-left: calc(1.5rem * ${level});
          padding-left: 2px;
        }

        .names {
          display: flex;
          height: 1.75rem;
          align-items: center;
          position: relative;
        }

        .names > :global(.indent) {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          width: 1px;
          height: 100%;
          margin-left: -1px;
        }

        .icon {
          width: 1.25rem;
          height: 100%;
          display: inline-flex;
          align-items: center;
          margin-right: 0.125rem;
        }

        .name {
          transition: opacity 100ms ease 0ms;
          color: ${theme.palette.accents_12};
          white-space: nowrap;
          font-size: 0.875rem;
        }

        .extra {
          font-size: 0.75rem;
          align-self: baseline;
          padding-left: 4px;
          color: ${theme.palette.accents_10};
        }

        .name:hover {
          opacity: 0.7;
          color: ${theme.palette.brand.primary[11]};
        }
      `}</style>
    </div>
  )
}

export default withDefaults(TreeLeaf, defaultProps)
