import Icon from "@aet/icons/macro"
import { useTranslation } from "react-i18next"
import { gql, useMutation, useQuery } from "~/generated/graphql"
import { LinkButton } from "./LinkButton"
import { FileActions, Popup, Section } from "./style"

const PREF = gql<"PopupPreferences">`
  query PopupPreferences {
    preferences {
      enabled
    }
  }
`

const TOGGLE = gql<"PopupToggle">`
  mutation PopupToggle($enabled: Boolean!) {
    setPreferences(preferences: { enabled: $enabled }) {
      enabled
    }
  }
`

const PowerButton: React.FC = () => {
  const { data: { preferences: prefs } = {} } = useQuery(PREF)

  const [togglePower] = useMutation(TOGGLE, {
    variables: { enabled: !prefs?.enabled },
  })

  if (!prefs) return null

  return (
    <LinkButton
      style={{ color: prefs.enabled ? "#0bb50b" : "#ccc" }}
      onClick={() => togglePower()}
    >
      <Icon icon="FaPowerOff" />
    </LinkButton>
  )
}

export const StateToggles: React.FC = () => {
  const { t } = useTranslation()

  return (
    <Section>
      <Popup.Block>
        <Popup.EntryLeft>{t("preferences.enabled")}</Popup.EntryLeft>
        <FileActions>
          <PowerButton />
        </FileActions>
      </Popup.Block>
    </Section>
  )
}
