import { validateGitLabGroupToken } from '@/editor/gitlabAccess'
import type { Path } from '@/router'
import { useNavigate } from '@/router'
import { Button, FormGroup, InputGroup, Intent } from '@blueprintjs/core'
import type { FC } from 'react'
import { memo, useCallback, useState } from 'react'
import TooltipLabel from '../Tooltips/TooltipLabel'
import { GITLAB_ACCESS_FORM } from '../assets/pageContent/definitions'
import type { GitlabConfig } from '../useGitlabStorage'
import useGitlabStorage from '../useGitlabStorage'

interface GitlabSettingsProps {
  prevPath: Path
}

const GitlabSettings: FC<GitlabSettingsProps> = ({ prevPath }) => {
  const [config, setConfig] = useGitlabStorage()
  const [host, setHost] = useState(config?.gitlabHost || '')
  const [groupPath, setGroupPath] = useState(config?.groupPath || '')
  const [token, setToken] = useState(config?.token)
  const [isTokenValid, setIsTokenValid] = useState<boolean | undefined>(true)
  const nav = useNavigate()

  const saveConfig = useCallback(
    async (newConfig?: GitlabConfig) => {
      if (!newConfig) return
      const result = await validateGitLabGroupToken(newConfig, newConfig.token)
      setIsTokenValid(result !== undefined)
      setConfig({ ...newConfig, groupId: result })
      if (result) nav(prevPath)
    },
    [prevPath]
  )

  return (
    <FormGroup
      helperText={!isTokenValid && 'Invalid access data'}
      intent={!isTokenValid ? Intent.DANGER : Intent.NONE}
    >
      <TooltipLabel label={GITLAB_ACCESS_FORM.host}>
        <InputGroup
          placeholder='Input gitlab host'
          value={host}
          onChange={e => setHost(e.target.value)}
        />
      </TooltipLabel>
      <TooltipLabel label={GITLAB_ACCESS_FORM.group}>
        <InputGroup
          placeholder='Input gitlab group'
          value={groupPath}
          onChange={e => setGroupPath(e.target.value)}
        />
      </TooltipLabel>
      <TooltipLabel label={GITLAB_ACCESS_FORM.token}>
        <InputGroup
          placeholder='Input group token'
          value={token}
          onChange={e => setToken(e.target.value)}
        />
      </TooltipLabel>
      <Button
        text='Save'
        intent='primary'
        onClick={() => saveConfig({ gitlabHost: host, groupPath, token })}
      />
    </FormGroup>
  )
}

export default memo(GitlabSettings)
