import styled from "@emotion/styled"
import { css } from "@emotion/css"
import { useEffect } from "react"
import { gql, useQuery } from "~/generated/graphql"
import { getActiveFile, useDispatch, useSelector } from "../../store"
import { updateTags } from "../../store/actions"
import { TagsInput } from "~/vendor/react-tag-input-component"

export const CurrentTags = gql<"CurrentTagsQuery">`
  query CurrentTagsQuery {
    tags
  }
`

export const Tags: FC<ClassNameProp> = ({ className }) => {
  const dispatch = useDispatch()
  const tags = useSelector(s => getActiveFile(s)?.tags)

  const { data: tagData, refetch } = useQuery(CurrentTags, {})

  useEffect(() => {
    void refetch()
  }, [tags, refetch])

  if (!tags) {
    return null
  }

  return (
    <TagsContainer className={className}>
      <TagsInput
        value={tags}
        onChange={tags => dispatch(updateTags(tags))}
        suggestions={tagData?.tags}
        tagRender={({ Tag, defaultProps }) => <Tag {...defaultProps} />}
        className={css`
          width: 100%;
          &:not(:hover) {
            border-color: transparent;
          }
        `}
      />
    </TagsContainer>
  )
}

const TagsContainer = styled.div`
  display: flex;
  margin: 10px 15px;
  line-height: 1.3em;
`
