import {
  useUsersQuery,
  useUserDeleteMutation,
  UsersDocument,
  Permission,
  useUpdatePermissionsMutation,
  UsersQuery,
} from '../../../src/gql'
import { FunctionComponent } from 'react'
import { TUser } from '../../../src/user/types'
import { AdminList } from '../../../src/app'
import theme from '../../../src/styles/theme'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faDumbbell, faUserNinja } from '@fortawesome/free-solid-svg-icons'

const AdminUser: FunctionComponent<{ item: TUser; className?: string }> = ({ item, className }) => {
  const [updatePermission, updateDate] = useUpdatePermissionsMutation({
    refetchQueries: [{ query: UsersDocument }],
  })
  const isAdmin = item.permissions?.includes(Permission.Admin)
  const isInstructor = item.permissions?.includes(Permission.Instructor)
  const { permissions = [] } = item

  return (
    <div className={className}>
      <div className='admin-training-title'>{item.name}</div>
      <div className='admin-training-email'>{item.email}</div>
      <div className='admin-training-permissions'>
        <button
          onClick={(event) => {
            const newPermissions = isInstructor
              ? permissions.filter((permission) => Permission.Instructor !== permission)
              : [...permissions, Permission.Instructor]
            updatePermission({ variables: { id: item.id, permissions: newPermissions } })
          }}
          title='Instructor'
          className={isInstructor ? 'true' : 'false'}
        >
          <FontAwesomeIcon icon={faDumbbell} height={16} />
        </button>
        <button
          onClick={(event) => {
            const newPermissions = isAdmin
              ? permissions.filter((permission) => Permission.Admin !== permission)
              : [...permissions, Permission.Admin]
            updatePermission({ variables: { id: item.id, permissions: newPermissions } })
          }}
          title='Admin'
          className={isAdmin ? 'true' : 'false'}
        >
          <FontAwesomeIcon icon={faUserNinja} height={16} />
        </button>
      </div>
      <style jsx>{`
        .${className} {
          display: flex;
        }
        .admin-training-title {
          width: 15%;
        }
        .admin-training-email {
          width: 65%;
        }
        .admin-training-permissions {
          width: 20%;
          text-align: left;
        }
        button {
          display: inline;
          margin: 0 0.4em;
          padding: 0;
          color: ${theme.colors.buttonBackground};
          background-color: transparent;
        }
        button.false {
          color: #5557;
        }
      `}</style>
    </div>
  )
}

const AdminUsers = () => {
  const props = {
    name: 'Users',
    adminMenu: '/admin/user',
    get: useUsersQuery,
    remove: useUserDeleteMutation,
    dataKey: 'users' as keyof UsersQuery,
    Component: AdminUser,
  }
  return <AdminList {...props} />
}

export default AdminUsers
