import { useUsersQuery, UsersQuery, Permission } from '../../graphql'
import { useFormHandler, InputPropsOptions } from '../form/forms'
import { useEffect } from 'react'

interface UserInputProps {
  inputProps: (name: string, options?: InputPropsOptions) => any
  subtree: string
}

const UserInput = ({ inputProps, subtree }: UserInputProps) => {
  console.log('user input', inputProps('name', { subtree }))
  return (
    <tr>
      <td><input type='checkbox' /></td>
      <td><input {...inputProps('name', { subtree })} /></td>
      <td><input {...inputProps('email', { subtree, label: 'e-mail' })} /></td>
      <td><input type='checkbox' {...inputProps('admin')} /></td>
      <td><input type='checkbox' {...inputProps('instructor')} /></td>
      <td><input {...inputProps('interests', { subtree })} /></td>
      <td><button>X</button></td>
    </tr>

  )
}

const initialData: UsersQuery = {
  users: []
}

const UserAdmin = () => {
  const { data, error, loading } = useUsersQuery()
  const { inputProps, values, setValues } = useFormHandler(initialData)

  useEffect(() => {
    if (data) console.log('data', { ...data })
    if (data && data.users) setValues({ ...data })
  }, [data])

  if (error) return <p>Error: {error.message}</p>
  if (loading) return <p>Loading...</p>

  return (
    <form>
      <table>
        <thead>
          <tr>
            <th></th>
            <th>Name</th>
            <th>Email</th>
            <th>Admin</th>
            <th>Instructor</th>
            <th>Interests</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {
            values.users.map((user, index) => (
              user && <UserInput key={user.id} inputProps={inputProps} subtree={`users.${index}`} />
            ))
          }
        </tbody>
      </table>
    </form>
  )
}

export default UserAdmin