import { Button, MenuItem } from '@blueprintjs/core'
import { Select } from '@blueprintjs/select'
import { css } from '@emotion/css'
import type { User } from '@inject/graphql/fragments/User.generated'
import { useChangeUserData } from '@inject/graphql/mutations/ChangeUserData.generated'
import type { AuthGroup } from '@inject/graphql/types'
import { useNotifyContext } from '@inject/shared/notification/contexts/NotifyContext'
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 [changeUserData, { loading }] = useChangeUserData()
  const { notify } = useNotifyContext()

  const [newGroup, setNewGroup] = useState(user.group)
  const [newIsActive, setNewIsActive] = useState(user.isActive)

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

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

  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<AuthGroup>
            fill
            onItemSelect={group => setNewGroup(group)}
            items={AUTH_GROUPS}
            popoverProps={{ minimal: true }}
            itemRenderer={(item, { handleClick }) => (
              <MenuItem
                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
