import React, { useState, ChangeEvent, useEffect } from 'react';
import { User } from '../types/user';

export interface UserFormProps {
  user: User
  onChange?: (user: User) => void
}

export function UserForm({ user, onChange }: UserFormProps) {  
  const [ state, setState ] = useState({
    changed: false,
    user: {
      name: '',
      email: '',
      createdAt: null,
      connectedAt: null,
      ...user,
    }
  });

  const onSaveClick = () => {
    if (!state.changed) return;
    if (typeof onChange !== 'function') return;
    onChange(state.user);
    setState(state => {
      return {
        ...state,
        changed: false,
      };
    })
  };
  
  const onUserAttrChange = function(attrName: string, evt: ChangeEvent<HTMLInputElement>) {
    const value = evt.currentTarget.value;
    setState(state => {
      return {
        ...state,
        changed: true,
        user: {
          ...state.user,
          [attrName]: value,
        }
      };
    });
  };

  return (
    <div className="form">
      <div className="field">
        <label className="label">Nom d'utilisateur</label>
        <div className="control">
          <input type="text" className="input" value={state.user.name} 
            onChange={onUserAttrChange.bind(null, "name")} />
        </div>
      </div>
      <div className="field">
        <label className="label">Adresse courriel</label>
        <div className="control">
          <p className="input is-static">{state.user.email}</p>
        </div>
      </div>
      <div className="field">
        <label className="label">Date de dernière connexion</label>
        <div className="control">
          <p className="input is-static">{state.user.connectedAt}</p>
        </div>
      </div>
      <div className="field">
        <label className="label">Date de création</label>
        <div className="control">
          <p className="input is-static">{state.user.createdAt}</p>
        </div>
      </div>
      <div className="buttons is-right">
        <button disabled={!state.changed} 
          className="button is-primary" onClick={onSaveClick}>Enregistrer</button>
      </div>
    </div>
  );
}