import { Button, MenuItem } from '@blueprintjs/core'
import { Select } from '@blueprintjs/select'
import { css } from '@emotion/css'
import type { User } from '@inject/graphql/fragment-types'
import { useTypedMutation } from '@inject/graphql/graphql'
import { ChangeUserData } from '@inject/graphql/mutations'
import { notify } from '@inject/shared/notification/engine'
import type { FC } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { AUTH_GROUPS } from '../UserTable/utils'

const wrapper = css`
  display: flex;
  gap: 0.5rem;
  justify-content: space-between;
`

const settings = css`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`

const settingRow = css`
  display: flex;
  gap: 0.5rem;
  align-items: center;
`

const settingName = css`
  font-weight: bolder;
`

const saveButton = css`
  align-self: flex-end;
`

interface UserDetailSettingProps {
  user: User
}

const UserDetailSetting: FC<UserDetailSettingProps> = ({ user }) => {
  const [{ fetching: loading }, changeUserData] =
    useTypedMutation(ChangeUserData)
  const [newGroup, setNewGroup] = useState(user.group)
  const [newIsActive, setNewIsActive] = useState(user.isActive)

  useEffect(() => {
    setNewGroup(user.group)
    setNewIsActive(user.isActive)
  }, [user])

  const handleButton = useCallback(() => {
    changeUserData({
      userId: user.id,
      group: newGroup === user.group ? undefined : newGroup,
      active: newIsActive === user.isActive ? undefined : newIsActive,
    }).catch(error => notify(error.message, { intent: 'danger' }))
  }, [
    changeUserData,
    user.id,
    user.group,
    user.isActive,
    newGroup,
    newIsActive,
  ])

  const saveDisabled = useMemo(
    () => newGroup === user.group && newIsActive === user.isActive,
    [newGroup, newIsActive, user.group, user.isActive]
  )

  return (
    <div className={wrapper}>
      <div className={settings}>
        <div className={settingRow}>
          <span className={settingName}>Group:</span>
          <Select<typeof newGroup>
            fill
            onItemSelect={group => setNewGroup(group)}
            items={AUTH_GROUPS}
            popoverProps={{ minimal: true }}
            itemRenderer={(item, { handleClick }) => (
              <MenuItem
                key={item}
                onClick={handleClick}
                text={item}
                active={item === newGroup}
              />
            )}
            filterable={false}
          >
            <Button
              alignText='left'
              fill
              rightIcon='double-caret-vertical'
              text={newGroup}
            />
          </Select>
        </div>
        <div className={settingRow}>
          <span className={settingName}>Active:</span>
          <Select<'yes' | 'no'>
            fill
            onItemSelect={isActive => setNewIsActive(isActive === 'yes')}
            items={['yes', 'no']}
            popoverProps={{ minimal: true }}
            itemRenderer={(item, { handleClick }) => (
              <MenuItem
                onClick={handleClick}
                text={item}
                active={item === (newIsActive ? 'yes' : 'no')}
              />
            )}
            filterable={false}
          >
            <Button
              alignText='left'
              fill
              rightIcon='double-caret-vertical'
              text={newIsActive ? 'yes' : 'no'}
            />
          </Select>
        </div>
      </div>

      <Button
        type='button'
        intent='primary'
        icon='floppy-disk'
        onClick={handleButton}
        loading={loading}
        disabled={saveDisabled}
        title={saveDisabled ? 'No changes' : undefined}
        className={saveButton}
      >
        Save
      </Button>
    </div>
  )
}

export default UserDetailSetting
