import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';
import CustomFixedTable from 'components/enhancers/CustomFixedTable';
import TableListItem from 'components/listItems/TableListItem';
import TextItem from 'components/items/TextItem';

import ModuleButton from 'components/items/ModuleButton';
import ModuleList from 'components/pageItems/ModuleList';
import options from 'config/models/videos';
import styleIdentifiers from './list.scss';

const EnhancedTable = CustomFixedTable(TableListItem);

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type ListProps = StateProps & DispatchProps & OwnProps;

const List = (props: ListProps) => {
  const {
    result,
    detail,
    getForm,
    lg,
    history,
    match: { params },
    dialogShow,
    dialogHide,
    exportPDF,
  } = props;

  // EXPORT FORM DATA
  function exportData() {
    dialogShow({
      id: 'custom',
      wrapperClassName: styles('dialog-wrapper'),
      children: (
        <div className={styles('dialog-content')}>
          <div className={styles('title')}>
            <TextItem path="Export form data" />
          </div>
          <div className={styles('button-container')}>
            <ModuleButton
              label="CSV"
              action={() =>
                exportPDF({
                  formId: detail._id,
                  callback: res => {
                    if (res.url) window.open(res.url, '_blank');
                    dialogHide('custom');
                  },
                })
              }
            />
          </div>
        </div>
      ),
    });
  }

  function renderActions() {
    return (
      <div className={styles('buttons')}>
        <ModuleButton noMargin icon="file-export" color="primary" action={exportData} relative />
      </div>
    );
  }

  function renderHeader() {
    const headers = [];

    if (detail && detail.formData) {
      for (let index = 0; index < detail.formData.length; index++) {
        const element = detail.formData[index];
        headers.push({
          title: element.title,
          key: `formData.${element.title}`,
          noUpdate: true,
        });
      }
    }

    return headers;
  }

  useEffect(() => {
    if (params.id) getForm({ id: params.id });
  }, [params.id]);

  return (
    <div className={styles('List')}>
      {detail && result && (
        <EnhancedTable
          virtual
          lg={lg}
          headers={renderHeader()}
          title={detail.title}
          loading={result.loading}
          loaded={result.loaded}
          itemProps={{
            noUpdate: true,
            actionDetail: e => history.push(`/forms/${detail._id}/${e._id}`),
          }}
          items={result.data && result.data.submissions}
          noCheckbox
          actions={renderActions()}
        />
      )}
    </div>
  );
};

export default List;
