import React, { FunctionComponent, useState, ChangeEvent, useEffect } from 'react';
import { DecisionSupportFileUpdaterProps } from './DecisionSupportFileUpdaterProps';
import { useDebounce } from '../../hooks/useDebounce';
import { asDate } from '../../util/date';

export interface ClarificationSectionProps extends DecisionSupportFileUpdaterProps {};

const ClarificationSectionName = 'clarification';

export const ClarificationSection: FunctionComponent<ClarificationSectionProps> = ({ dsf, updateDSF, readOnly }) => {
  const [ state, setState ] = useState({
    changed: false,
    section: {
      objectives: '',
      motivations: '',
      scope: '',
      nature: '',
      deadline: undefined,
      hasDeadline: false,
    }
  });

  useEffect(() => {
    if (!state.changed) return;
    updateDSF({ ...dsf, sections: { ...dsf.sections, [ClarificationSectionName]: { ...state.section }} })
    setState(state => ({ ...state, changed: false }));
  }, [state.changed]);

  useEffect(() => {
    if (!dsf.sections[ClarificationSectionName]) return;
    setState(state => ({ ...state, changed: false, section: {...state.section, ...dsf.sections[ClarificationSectionName] }}));
  }, [dsf.sections[ClarificationSectionName]]);

  const onTitleChange = (evt: ChangeEvent<HTMLInputElement>) => {
    const title = (evt.currentTarget).value;
    updateDSF({ ...dsf, title });
  };

  const onSectionAttrChange = (attrName: string, evt: ChangeEvent<HTMLInputElement>) => {
    const target = evt.currentTarget;
    const value = target.hasOwnProperty('checked') ? target.checked : target.value;
    setState(state => ({ ...state, changed: true, section: {...state.section, [attrName]: value }}));
  };

  const onDeadlineChange = (evt: ChangeEvent<HTMLInputElement>) => {
    const deadline = evt.currentTarget.valueAsDate;
    setState(state => ({ ...state, changed: true, section: { ...state.section, deadline }}));
  };

  return (
    <section>
      <div className="box">
        <div className="field">
          <label className="label is-medium">Intitulé du dossier</label>
          <div className="control">
            <input className="input is-medium" type="text" readOnly={readOnly} value={dsf.title} onChange={onTitleChange} />
          </div>
        </div>
        <div className="field">
          <label className="label is-medium">Quelle décision devons nous prendre ?</label>
          <div className="control">
            <textarea className="textarea is-medium"
              readOnly={readOnly}
              value={state.section.objectives}
              onChange={onSectionAttrChange.bind(null, 'objectives')}
              placeholder="Décrire globalement les tenants et aboutissants de la décision à prendre." 
              rows={10}>
            </textarea>
          </div>
          <p className="help is-info"><i className="fa fa-info-circle"></i> Ne pas essayer de rentrer trop dans les détails ici. Préférer l'utilisation des annexes et y faire référence.</p>
        </div>
        <div className="field">
          <label className="label is-medium">Pourquoi devons nous prendre cette décision ?</label>
          <div className="control">
            <textarea className="textarea is-medium"
              readOnly={readOnly}
              value={state.section.motivations}
              onChange={onSectionAttrChange.bind(null, 'motivations')}
              placeholder="Décrire pourquoi il est important de prendre cette décision." 
              rows={10}>
            </textarea>
          </div>
          <p className="help is-info"><i className="fa fa-info-circle"></i> Penser à indiquer si des obligations légales pèsent sur cette prise de décision.</p>
        </div>
        <div className="field">
          <label className="label is-medium">Portée de la décision</label>
          <div className="control">
            <div className="select is-medium">
              <select
                disabled={readOnly}
                onChange={onSectionAttrChange.bind(null, 'scope')} 
                value={state.section.scope}>
                <option></option>
                <option value="individual">Individuelle</option>
                <option value="identified-group">Groupe identifié</option>
                <option value="collective">Collective</option>
              </select>
            </div>
          </div>
        </div>
        <div className="field">
          <label className="label is-medium">Nature de la décision</label>
          <div className="control">
            <div className="select is-medium">
              <select
                disabled={readOnly}
                onChange={onSectionAttrChange.bind(null, 'nature')} 
                value={state.section.nature}>
                <option></option>
                <option value="operational">Opérationnelle</option>
                <option value="tactic">Tactique</option>
                <option value="strategic">Stratégique</option>
              </select>
            </div>
          </div>
        </div>
        
        <div className="columns">
          <div className="column">
            <label className="checkbox">
              <input type="checkbox"
                className="is-medium"
                disabled={readOnly}
                onChange={onSectionAttrChange.bind(null, 'hasDeadline')}
                checked={state.section.hasDeadline} />
              <span className="ml-1 has-text-weight-bold is-size-5">Existe t'il une échéance particulière pour cette décision ?</span>
            </label>
            <div className="field">
              <div className="control">
                <input disabled={!state.section.hasDeadline}
                  readOnly={readOnly}
                  value={state.section.deadline ? asDate(state.section.deadline).toISOString().substr(0, 10) : ''}
                  onChange={onDeadlineChange}
                  type="date" className="input is-medium" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};