import React, { FunctionComponent, useState, ChangeEvent, useEffect } from 'react';
import { DecisionSupportFileUpdaterProps } from './DecisionSupportFileUpdaterProps';

export interface DecisionReportSectionProps extends DecisionSupportFileUpdaterProps {};

const DecisionReportSectionName = 'decision-report';

export const DecisionReportSection: FunctionComponent<DecisionReportSectionProps> = ({ dsf, updateDSF, readOnly }) => {
  const [ state, setState ] = useState({
    changed: false,
    section: {
      report: "",
    }
  });

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

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

  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 }}));
  };

  return (
    <section>
      <div className="field">
        <label className="label is-medium">Compte rendu du vote</label>
        <div className="control">
          <textarea className="textarea is-medium"
            readOnly={readOnly}
            value={state.section.report}
            onChange={onSectionAttrChange.bind(null, 'report')}
            rows={20}>
          </textarea>
        </div>
        <p className="help is-info"><i className="fa fa-info-circle"></i> Penser à indiquer le résultat du vote et les éléments de contexte liés à la prise de décision.</p>
      </div>
    </section>
  );
};