import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import adminConfig from 'config/admin';
import MosaicStructure from 'components/enhancers/MosaicStructure';
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 GenericDisplayFields from 'components/pageItems/GenericDisplayFields';
import ModuleDropActions from 'components/pageItems/ModuleDropActions';
import styleIdentifiers from './detail.scss';
import Permissions from '../Permissions';

const styles = classNames.bind(styleIdentifiers);

const GenericStructure = MosaicStructure(GenericDisplayFields);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type DetailProps = StateProps & DispatchProps & OwnProps;

const Detail = (props: DetailProps) => {
  const {
    loadData,
    publishArticle,
    unpublishArticle,
    dialogShow,
    detail,
    lg,
    history,
    match: { params },
    location,
  } = props;

  const options = adminConfig?.adminBlog[params.resource];

  function setPublicationStatus() {
    if (detail.data.published) {
      unpublishArticle({ id: detail.data._id });
    } else if (
      detail.data.seo &&
      detail.data.content &&
      detail.data.thumbnail &&
      detail.data.urls &&
      detail.data.cover &&
      detail.data.title &&
      detail.data.authorId
    ) {
      publishArticle({ id: detail.data._id });
    } else {
      dialogShow({
        data:
          'To publish an article it must have content, seo, urls, title, author, cover and a thumbnail.',
      });
    }
  }

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

  const listFields = fieldsToList(options.model);

  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(`/blog/${params.resource}/${detail.data._id}/edit`)}
                >
                  <TextItem path="admin.buttons.edit" />
                </div>
              </div>
              {detail && detail.data && (
                <>
                  <div className={styles('actions-items')}>
                    <div className={styles('item')} onClick={() => setPublicationStatus()}>
                      <TextItem
                        path={
                          !detail.data.published ? 'admin.blog.published' : 'admin.blog.unpublished'
                        }
                      />
                    </div>
                  </div>
                  {detail.data.published && (
                    <div
                      className={styles('actions-items')}
                      onClick={() => history.push(`${location.pathname}/preview`)}
                    >
                      {config.blog && config.blog.internalPreview ? (
                        <div className={styles('item')}>
                          <TextItem path="admin.blog.preview" />
                        </div>
                      ) : (
                        <a
                          style={{ display: 'block', color: 'inherit' }}
                          className={styles('item')}
                          href={`${(config.blog && config.blog.previewArticle) ||
                            detail.data.urls[lg]}`}
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          <TextItem path="admin.blog.preview" />
                        </a>
                      )}
                    </div>
                  )}
                </>
              )}
            </ModuleDropActions>
          )}
        </div>
      </div>
      <div
        className={styles('container', params && params.resource === 'articles' && 'with-sub-nav')}
      >
        {params && params.resource === 'articles' && (
          <div className={styles('nav-container')}>
            {detail && detail.data && (
              <div className={styles('nav-content')}>
                <div className={styles('item-wrapper')}>
                  <NavLink
                    to={`/blog/${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={`/blog/${params.resource}/${detail.data._id}/permissions`}
                    className={styles('item', 'link-wrapper')}
                    activeClassName={styles('state-active')}
                  >
                    <span>Permissions</span>
                  </NavLink>
                </div>
              </div>
            )}
          </div>
        )}
        <div className={styles('content')}>
          <Switch>
            <Route
              path="/blog/:resource/:id/detail"
              component={() => (
                <GenericStructure
                  transformedData={options.transformedData}
                  scrollableColumns
                  minWidth={config.widthDetailColumn}
                  data={detail && detail.data}
                  items={listFields}
                  oneSection={listFields.length === 1}
                />
              )}
            />
            <Route path="/blog/:resource/:id/permissions" component={Permissions} />
            <Route
              component={() => (
                <GenericStructure
                  transformedData={options.transformedData}
                  scrollableColumns
                  minWidth={config.widthDetailColumn}
                  data={detail && detail.data}
                  items={listFields}
                  oneSection={listFields.length === 1}
                />
              )}
            />
          </Switch>
        </div>
      </div>
    </div>
  );
};

export default Detail;
