import {
  Button,
  Checkbox,
  Collapse,
  FormGroup,
  InputGroup,
  Label,
  NumericInput,
} from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Config } from '@inject/graphql/fragment-types'
import type { ConfigOverrideInput } from '@inject/graphql/urql/cache-typing'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { Dispatch, FC, SetStateAction } from 'react'
import { useState } from 'react'

const marginBottom = css`
  margin-bottom: 1rem;
`

interface OverrideConfigProps {
  className?: string
  definitionConfig: Config | undefined
  value: Partial<ConfigOverrideInput> | undefined
  setValue: Dispatch<SetStateAction<Partial<ConfigOverrideInput> | undefined>>
}

const OverrideConfig: FC<OverrideConfigProps> = ({
  definitionConfig,
  value,
  setValue,
  className,
}) => {
  const [isOpen, setIsOpen] = useState(false)

  return (
    <div className={className}>
      <Button
        className={isOpen ? marginBottom : undefined}
        onClick={() => {
          if (isOpen) {
            setValue(undefined)
          }
          setIsOpen(!isOpen)
        }}
        disabled={!definitionConfig}
        title={definitionConfig ? 'Override config' : 'Select a definition'}
      >
        Override config
      </Button>
      <Collapse isOpen={isOpen}>
        {definitionConfig && (
          <>
            <Label style={{ width: '100%' }}>
              Exercise duration (in minutes)
              <NumericInput
                fill
                value={
                  value?.exerciseDuration || definitionConfig.exerciseDuration
                }
                minorStepSize={null}
                onValueChange={value => {
                  if (value > 0) {
                    setValue(prev => ({ ...prev, exerciseDuration: value }))
                  }
                }}
                min={1}
                title='Exercise duration (in minutes)'
                placeholder='60'
                style={{ margin: 0 }}
              />
            </Label>

            <Label style={{ width: '100%' }}>
              Custom email suffix
              <InputGroup
                placeholder='mail.com'
                value={
                  value?.customEmailSuffix || definitionConfig.customEmailSuffix
                }
                onChange={e =>
                  setValue(prev => ({
                    ...prev,
                    customEmailSuffix: e.target.value,
                  }))
                }
              />
            </Label>

            <FormGroup
              style={{ width: '100%' }}
              label='Update interval'
              labelInfo='(in seconds)'
              helperText='How often the exercise status is updated'
            >
              <NumericInput
                fill
                value={
                  value?.updateIntervalS || definitionConfig.updateIntervalS
                }
                minorStepSize={null}
                onValueChange={value => {
                  if (value > 0) {
                    setValue(prev => ({ ...prev, updateIntervalS: value }))
                  }
                }}
                min={1}
                title='Update interval (in seconds)'
                placeholder='10'
                style={{ margin: 0 }}
              />
            </FormGroup>

            <Checkbox
              label='Show exercise time'
              checked={
                notEmpty(value?.showExerciseTime)
                  ? value.showExerciseTime
                  : definitionConfig.enabledFeatures.includes(
                      'SHOW_EXERCISE_TIME'
                    )
              }
              onChange={e =>
                setValue(prev => ({
                  ...prev,
                  showExerciseTime: e.target.checked,
                }))
              }
            />

            <Checkbox
              label='Enable emails between teams'
              checked={
                notEmpty(value?.emailBetweenTeams)
                  ? value.emailBetweenTeams
                  : definitionConfig.enabledFeatures.includes(
                      'EMAIL_BETWEEN_TEAMS'
                    )
              }
              onChange={e =>
                setValue(prev => ({
                  ...prev,
                  emailBetweenTeams: e.target.checked,
                }))
              }
            />

            <Label style={{ width: '100%', marginBottom: 0 }}>
              Custom team names
              <InputGroup
                placeholder='team1, team2, ..., teamN'
                value={value?.customTeamNames?.join(', ')}
                onChange={e =>
                  setValue(prev => ({
                    ...prev,
                    customTeamNames: e.target.value
                      .split(',')
                      .map(s => s.trim()),
                  }))
                }
              />
            </Label>
          </>
        )}
      </Collapse>
    </div>
  )
}

export default OverrideConfig
