import React, { useEffect, useState, Fragment } from 'react';
import { Page } from '../Page';
import { useParams } from 'react-router';
import { useWorkgroups } from '../../gql/queries/workgroups';
import { useUserProfile } from '../../gql/queries/profile';
import { MembersPanel } from './MembersPanel';
import { User } from '../../types/user';
import { InfoPanel } from './InfoPanel';
import { Workgroup } from '../../types/workgroup';
import { useJoinWorkgroupMutation, useLeaveWorkgroupMutation, useCloseWorkgroupMutation } from '../../gql/mutations/workgroups';
import { TimelinePanel } from './TimelinePanel';
import { DecisionSupportFilePanel } from './DecisionSupportFilePanel';

export function WorkgroupPage() {
  const { id } = useParams<any>();
  const { workgroups } = useWorkgroups({
    variables:{
      filter: { 
        ids: [id],
      }
    }
  });
  const { user } = useUserProfile();
  
  const [ joinWorkgroup ] = useJoinWorkgroupMutation();
  const [ leaveWorkgroup ] = useLeaveWorkgroupMutation();
  const [ closeWorkgroup ] = useCloseWorkgroupMutation();

  const [ state, setState ] = useState({
    userProfileId: '',
    workgroup: {
      id: '',
      name: '',
      closedAt: null,
      createdAt: null,
      members: [],
    }
  });

  useEffect(() => {
    setState(state => ({...state, workgroup:{ ...state.workgroup, ...workgroups[0]}}));
  }, [workgroups]);

  useEffect(() => {
    setState(state => ({...state, userProfileId: user.id }));
  }, [user]);

  const onJoinWorkgroupClick = () => {
    joinWorkgroup({
      variables: {
        workgroupId: state.workgroup.id,
      }
    });
  }

  const onLeaveWorkgroupClick = () => {
    leaveWorkgroup({
      update: (cache, result) => {
        cache.modify({
          id: cache.identify(result.data.leaveWorkgroup),
          fields: {
            members(existingMembers, { readField }) {
              return existingMembers.filter(
                user => state.userProfileId !== readField('id', user)
              );
            },
          },
        });
      },
      variables: {
        workgroupId: state.workgroup.id,
      }
    });
  }

  const onCloseWorkgroupClick = () => {
    closeWorkgroup({
      variables: {
        workgroupId: state.workgroup.id,
      }
    });
  }

  const isNew = state.workgroup.id === '';
  const isWorkgroupMember = state.workgroup.members.some(u => u.id === state.userProfileId);
  const isClosed = state.workgroup.closedAt !== null;

  return (
    <Page title="Groupe de travail">
      <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">Groupe de travail</h3>
                  </div>
                </div> :
                <div className="level-item">
                  <div>
                    <h2 className="is-size-3 title is-spaced">{state.workgroup.name}</h2>
                    <h3 className="is-size-5 subtitle">Groupe de travail <span className="is-italic">{ isClosed ? '(clos)' : null }</span></h3>
                  </div>
                </div>
              }
            </div>
            <div className="level-right">
              <div className="buttons is-right level-item">
                {
                  isNew || isClosed ? null :
                  <Fragment>
                    {
                      isWorkgroupMember ?
                      <Fragment>
                        <button onClick={onLeaveWorkgroupClick} className="button is-info is-warning is-medium">
                          <span>Quitter</span>
                          <span className="icon"><i className="fas fa-sign-out-alt"></i></span>
                        </button>
                        <button onClick={onCloseWorkgroupClick} className="button is-danger is-medium">
                          <span>Clore</span>
                          <span className="icon"><i className="far fa-times-circle"></i></span>
                        </button>
                      </Fragment> :
                      <button onClick={onJoinWorkgroupClick} className="button is-info is-medium">
                        <span>Rejoindre</span>
                        <span className="icon"><i className="fas fa-user-plus"></i></span>
                      </button>
                    }
                  </Fragment>
                }
              </div>
            </div>
          </div>
          <div className="columns">
            <div className="column is-4">
              <InfoPanel workgroup={state.workgroup as Workgroup} />
            </div>
            <div className="column is-4">
              <MembersPanel users={state.workgroup.members as User[]} />
              <DecisionSupportFilePanel workgroupId={state.workgroup.id} />
            </div>
            <div className="column is-4">
              <TimelinePanel workgroup={state.workgroup} />
            </div>
          </div>
        </section>
      </div>
    </Page>
  );
}

export default WorkgroupPage;