import React, { FunctionComponent, useState, useEffect } from 'react';
import { Page } from '../Page';
import { ClarificationSection } from './ClarificationSection';
import { MetadataPanel } from './MetadataPanel';
import { AppendixPanel } from './AppendixPanel';
import { DecisionSupportFile, newDecisionSupportFile, DecisionSupportFileStatus } from '../../types/decision';
import { useParams, useHistory } from 'react-router';
import { useDecisionSupportFiles } from '../../gql/queries/dsf';
import { useCreateDecisionSupportFileMutation, useUpdateDecisionSupportFileMutation } from '../../gql/mutations/dsf';
import { OptionsSection } from './OptionsSection';
import { useIsAuthorized } from '../../gql/queries/authorization';
import { TimelinePanel } from './TimelinePanel';

export interface DecisionSupportFilePageProps {

};

export const DecisionSupportFilePage: FunctionComponent<DecisionSupportFilePageProps> = () => {
  const { id } = useParams();
  const history = useHistory();
  const { decisionSupportFiles } = useDecisionSupportFiles({
    variables:{
      filter: {
        ids: id !== 'new' ? [id] : undefined,
      }
    },
  });

  const [ state, setState ] = useState({ 
    dsf: newDecisionSupportFile(),
    saved: true,
    selectedTabIndex: 0,
  });


  const { isAuthorized } = useIsAuthorized({
    variables: {
      action: 'update',
      object: {
        decisionSupportFileId: state.dsf.id,
      }
    }
  }, id === 'new');

  useEffect(() => {
    const dsf = decisionSupportFiles.length > 0 && decisionSupportFiles[0].id === id ? decisionSupportFiles[0] : {};
    setState(state => ({ ...state, dsf: { ...state.dsf, ...dsf }}))
  }, [ decisionSupportFiles ]);

  const selectTab = (tabIndex: number) => {
    setState(state => ({ ...state, selectedTabIndex: tabIndex }));
  };

  const updateDSF = (dsf: DecisionSupportFile) => {
    setState(state => {
      return { ...state, saved: false, dsf: { ...state.dsf, ...dsf } };
    });
  };

  const [ createDecisionSupportFile ] = useCreateDecisionSupportFileMutation();
  const [ updateDecisionSupportFile ] = useUpdateDecisionSupportFileMutation();

  const saveDSF = () => {
    const changes = {
      title: state.dsf.title !== '' ? state.dsf.title : undefined,
      status: state.dsf.status,
      workgroupId: state.dsf.workgroup ? state.dsf.workgroup.id : undefined,
      sections: state.dsf.sections,
    };

    if (!changes.workgroupId) return;

    if (state.dsf.id === '') {
      createDecisionSupportFile({
        variables: { changes },
      }).then(({ data }) => {
        history.push(`/decisions/${data.createDecisionSupportFile.id}`);
      });
    } else {
      updateDecisionSupportFile({
        variables: { changes, id: state.dsf.id },
      }).then(({ data }) => {
        setState(state => {
          return { ...state, saved: true, dsf: { ...state.dsf, ...data.updateDecisionSupportFile } };
        });
      });
    }
  };

  const canSave = !!state.dsf.workgroup && !state.saved;
  const isNew = state.dsf.id === '';
  const isClosed = state.dsf.status === DecisionSupportFileStatus.Closed;

  return (
    <Page title="Dossier d'Aide à la Décision">
      <div className="container is-fluid">
        <section className="mt-5">
          <div className="level">
            <div className="level-left">
              {
                isNew ?
                <div className="level-item">
                  <div>
                    <h2 className="is-size-3 title is-spaced">Nouveau</h2>
                    <h3 className="is-size-5 subtitle">Dossier d'Aide à la Décision</h3>
                  </div>
                </div> :
                <div className="level-item">
                  <div>
              <h2 className="is-size-3 title is-spaced">{state.dsf.title} <span className={`ml-3 tag is-warning is-medium ${ isAuthorized ? 'is-hidden' : ''}`}>Lecture seule</span></h2>
                    <h3 className="is-size-5 subtitle">Dossier d'Aide à la Décision <span className="is-italic">{ isClosed ? '(clos)' : null }</span></h3>
                  </div>
                </div>
              }
            </div>
            <div className="level-right">
              <div className="level-item buttons">
                {
                  isAuthorized ?
                  <button className="button is-medium is-success" disabled={!canSave} onClick={saveDSF}>
                    <span className="icon"><i className="fa fa-save"></i></span>
                    <span>Enregistrer</span>
                  </button> :
                  null
                }
              </div>
            </div>
          </div>
        </section>
        <div className="columns mt-3">
          <div className="column is-8">
            <div className="tabs is-medium is-toggle">
              <ul>
                <li className={`has-background-white ${state.selectedTabIndex === 0 ? 'is-active': ''}`}
                  onClick={selectTab.bind(null, 0)}>
                  <a>
                    <span className="icon is-small"><i className="fas fa-pen" aria-hidden="true"></i></span>
                    <span>Clarifier la proposition</span>
                  </a>
                </li>
                <li className={`has-background-white ${state.selectedTabIndex === 1 ? 'is-active': ''}`} 
                    onClick={selectTab.bind(null, 1)}>
                  <a>
                    <span className="icon is-small"><i className="fas fa-search" aria-hidden="true"></i></span>
                    <span>Explorer les options</span>
                  </a>
                </li>
                <li className={`has-background-white ${state.selectedTabIndex === 2 ? 'is-active': ''}`} 
                    onClick={selectTab.bind(null, 2)}>
                  <a>
                    <span className="icon is-small"><i className="fas fa-person-booth" aria-hidden="true"></i></span>
                    <span>Prendre la décision</span>
                  </a>
                </li>
              </ul>
            </div>
            {
              state.selectedTabIndex === 0 ?
              <ClarificationSection readOnly={!isAuthorized} dsf={state.dsf} updateDSF={updateDSF} /> :
              null
            }
            {
              state.selectedTabIndex === 1 ?
              <OptionsSection readOnly={!isAuthorized} dsf={state.dsf} updateDSF={updateDSF} /> :
              null
            }
          </div>
          <div className="column is-4">
            <MetadataPanel readOnly={!isAuthorized} dsf={state.dsf} updateDSF={updateDSF} />
            <AppendixPanel dsf={state.dsf} />
            <TimelinePanel dsf={state.dsf} />
          </div>
        </div>
      </div>
    </Page>
  );
};