import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import adminConfig from 'config/admin';

import { fieldsToList } from 'store/utils/adminHelpers';
import ModuleButton from 'components/items/ModuleButton';
import config, { viewConfig } from 'config/general';
import { NavLink, Switch, Route } from 'react-router-dom';
import ModuleDetailStructure from 'components/enhancers/ModuleDetailStructure';
import ModuleDisplayFields from 'components/pageItems/ModuleDisplayFields';
import ModuleDropActions from 'components/pageItems/ModuleDropActions';
import styleIdentifiers from './detail.scss';
import Participant from '../Participant';

const styles = classNames.bind(styleIdentifiers);

// const GenericStructure = MosaicStructure(GenericDisplayFields);

const GenericStructure = ModuleDetailStructure(ModuleDisplayFields);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type DetailProps = StateProps & DispatchProps & OwnProps;

const Detail = (props: DetailProps) => {
  const {
    loadData,
    detail,
    lg,
    history,
    publishEvent,
    unpublishEvent,
    exportParticipant,
    exportParticipantPDF,
    match: { params },
    dialogShow,
    dialogHide,
  } = props;

  const options = adminConfig.adminEvent[params.resource];

  function renderStructureDetail() {
    return (
      <GenericStructure
        transformedData={options.transformedData}
        scrollableColumns
        minWidth={config.widthDetailColumn}
        data={detail && detail.data}
        items={fieldsToList(options.model)}
      />
    );
  }

  function managePublish() {
    const data = detail.data;
    if (data) {
      if (data.published) unpublishEvent({ id: data._id });
      else publishEvent({ id: data._id });
    }
  }

  function exportPart() {
    if (detail && detail.data) {
      dialogShow({
        id: 'custom',
        wrapperClassName: styles('dialog-wrapper'),
        children: (
          <div className={styles('container-dialog')}>
            <div className={styles('title')}>
              <TextItem path="Export participant file type" />
            </div>
            <div className={styles('button-container')}>
              <ModuleButton
                label="CSV"
                action={() =>
                  exportParticipant({
                    eventId: detail.data._id,
                    callback: res => {
                      if (res.url) window.open(res.url, '_blank');
                      dialogHide('custom');
                    },
                  })
                }
              />
              <ModuleButton
                label="PDF"
                action={() =>
                  exportParticipantPDF({
                    eventId: detail.data._id,
                    callback: res => {
                      if (res.url) window.open(res.url, '_blank');
                      dialogHide('custom');
                    },
                  })
                }
              />
            </div>
          </div>
        ),
      });
    }
  }

  useEffect(() => {
    loadData({
      options,
      apiInput: { id: params.id },
    });
  }, [params.id]);

  return (
    <div className={styles('Detail', 'header')}>
      <div className={styles('header')}>
        <h1>{detail && detail.data && detail.data.title && detail.data.title[lg]}</h1>
        <div className={styles('actions')}>
          <ModuleButton
            noMargin
            relative
            label="admin.buttons.back"
            action={() => history.goBack()}
            color={viewConfig.colorBack}
          />
          {detail && detail.data && (
            <ModuleDropActions
              label="Actions"
              colorModule="primary"
              toggleContent
              buttonComponent
              className={styles('dropdown')}
            >
              <div className={styles('actions-items')}>
                <div
                  className={styles('item')}
                  onClick={() => history.push(`/event/${params.resource}/${detail.data._id}/edit`)}
                >
                  <TextItem path="admin.buttons.edit" />
                </div>
                {params.resource === 'events' && (
                  <>
                    <div className={styles('item')} onClick={managePublish}>
                      <TextItem path={detail.data.published ? 'Unpublish' : 'Publish'} />
                    </div>
                    <div className={styles('item')} onClick={exportPart}>
                      <TextItem path="Export participants" />
                    </div>
                  </>
                )}
              </div>
            </ModuleDropActions>
          )}
        </div>
      </div>
      <div
        className={styles('container', params && params.resource === 'events' && 'with-sub-nav')}
      >
        {params && params.resource === 'events' && (
          <div className={styles('nav-container')}>
            {detail && detail.data && (
              <div className={styles('nav-content')}>
                <div className={styles('item-wrapper')}>
                  <NavLink
                    to={`/event/${params.resource}/${detail.data._id}/detail`}
                    className={styles('item', 'link-wrapper')}
                    activeClassName={styles('state-active')}
                  >
                    <span>Detail</span>
                  </NavLink>
                </div>
                <div className={styles('item-wrapper')}>
                  <NavLink
                    to={`/event/${params.resource}/${detail.data._id}/participants`}
                    className={styles('item', 'link-wrapper')}
                    activeClassName={styles('state-active')}
                  >
                    <span>Participants</span>
                  </NavLink>
                </div>
              </div>
            )}
          </div>
        )}
        {detail && detail.data && (
          <div className={styles('content')}>
            <Switch>
              <Route path="/event/:resource/:id/detail" component={() => renderStructureDetail()} />
              <Route path="/event/:resource/:id/participants" component={Participant} />
              <Route component={() => renderStructureDetail()} />
            </Switch>
          </div>
        )}
      </div>
    </div>
  );
};

export default Detail;
