import React, { useState, ChangeEvent, useEffect } from 'react';
import { Workgroup } from '../../types/workgroup';

export interface InfoFormProps {
  workgroup: Workgroup
  onChange?: (workgroup: Workgroup) => void
}

export function InfoForm({ workgroup, onChange }: InfoFormProps) {  
  const [ state, setState ] = useState({
    changed: false,
    workgroup: {
      id: workgroup && workgroup.id ? workgroup.id : '',
      name: workgroup && workgroup.name ? workgroup.name : '',
      createdAt: workgroup && workgroup.createdAt ? workgroup.createdAt : null,
      closedAt: workgroup && workgroup.closedAt ? workgroup.closedAt : null,
    }
  });

  useEffect(() => {
    setState({
      changed: false,
      workgroup: {
        id: workgroup && workgroup.id ? workgroup.id : '',
        name: workgroup && workgroup.name ? workgroup.name : '',
        createdAt: workgroup && workgroup.createdAt ? workgroup.createdAt : null,
        closedAt: workgroup && workgroup.closedAt ? workgroup.closedAt : null,
      }
    });
  }, [workgroup]);

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

  return (
    <div className="form" style={{width: '100%'}}>
      <div className="field">
        <label className="label">Nom du groupe</label>
        <div className="control">
          <input type="text" className="input" value={state.workgroup.name} 
            onChange={onWorkgroupAttrChange.bind(null, "name")} />
        </div>
      </div>
      {
        state.workgroup.createdAt ?
        <div className="field">
          <label className="label">Date de création</label>
          <div className="control">
            <p className="input is-static">{state.workgroup.createdAt}</p>
          </div>
        </div>:
        null
      }
      {
        state.workgroup.closedAt ?
        <div className="field">
          <label className="label">Date de clôture</label>
          <div className="control">
            <p className="input is-static">{state.workgroup.closedAt}</p>
          </div>
        </div>:
        null
      }
      <div className="buttons is-right">
        <button disabled={!state.changed} 
          className="button is-success" onClick={onSaveClick}>
          <span>Enregistrer</span>
          <span className="icon"><i className="fa fa-save"></i></span>
        </button>
      </div>
    </div>
  );
}