import { memo } from "react"
import { useTranslation } from "react-i18next"
import { css } from "@emotion/css"
import Icon from "@aet/icons/macro"
import { useEvent } from "@aet/hooks"
import { gql, useMutation, useQuery } from "~/generated/graphql"
import { FILE_FRAGMENT } from "~/options/fragments"
import { openFile } from "~/options/store/actions"
import { GET_FILES } from "./index"
import { removeTypeName } from "~/shared/removeTypeName"
import { useDispatch } from "~/options/store"
import { Pill } from "~/shared/styled"
import { GLOBAL_STYLE_ID } from "~/shared"

const CURRENT_GLOBAL_STYLE = gql<"CreateGlobalStyleQuery">`
  query CreateGlobalStyleQuery($id: ID!) {
    file(id: $id) {
      id
    }
  }
`

const CREATE_FILE = gql<"CreateGlobalStyle">`
  ${FILE_FRAGMENT}
  mutation CreateGlobalStyle {
    createGlobalStyle {
      ...FileFragment
    }
  }
`

export const AddGlobalFileButton = memo(({ onClose }: { onClose: () => void }) => {
  const { t } = useTranslation()
  const dispatch = useDispatch()

  const { data } = useQuery(CURRENT_GLOBAL_STYLE, {
    variables: { id: GLOBAL_STYLE_ID },
  })
  const [createFile] = useMutation(CREATE_FILE, {
    refetchQueries: [{ query: GET_FILES }],
  })

  const onClick = useEvent(async (e: React.MouseEvent) => {
    e.preventDefault()

    const { data } = await createFile()
    dispatch(openFile(removeTypeName(data!.createGlobalStyle)))
    onClose()
  })

  if (data?.file) {
    return null
  }

  return (
    <>
      <Pill
        type="button"
        onClick={onClick}
        className={css`
          width: 100%;
        `}
      >
        <Icon icon="BsGlobe" />
        {t("file.createGlobalStyle")}
      </Pill>
      <br />
      <hr />
    </>
  )
})
