import React, { useState, useEffect } from 'react';
import moment from 'moment';
import { faCircleCheck, faComment, faWrench } from '@fortawesome/free-solid-svg-icons';
import { connect } from 'react-redux';
import { analyticsActions } from '../apis';
import { PlussCore } from '../feature.config';
import { values } from '../values.config';

const { Analytics, Session, Components } = PlussCore;

const getInitialState = () => ({
  requests: 0,
  prevRequests: 0,
  completedRequests: 0,
  prevCompletedRequests: 0,
  comments: 0,
  prevComments: 0,
  isLoading: true,
});

// AnalyticsHub Component
const AnalyticsHub = ({ startTime, endTime, auth, prevText, dayCount, strings }) => {
  const [analyticsData, setAnalyticsData] = useState(getInitialState());
  const [isExportOpen, setIsExportOpen] = useState(false);

  const hasAccess = Session.validateAccess(auth.site, values.permissionMaintenanceTracking, auth);
  if (!hasAccess) {
    return null;
  }

  const featureTitle = ((key) => {
    if (!strings || !strings.sideNav || !strings.sideNav[key]) {
      return values.textMenuTitle;
    }
    return strings.sideNav[key];
  })();

  const exportColumns = [
    { label: 'Select All', key: '' },
    { label: 'Start Date', key: 'startDate' },
    { label: 'End Date', key: 'endDate' },
    { label: `${values.textSingularName}s`, key: 'requests' },
    { label: `Completed ${values.textSingularName}s`, key: 'completedRequests' },
    { label: 'Comments', key: 'comments' },
  ];

  useEffect(() => {
    getData();
  }, [startTime, endTime]);

  const getData = async () => {
    setAnalyticsData(getInitialState());
    // Load analytics data here using startTime and endTime
    const timeDifference = endTime - startTime;
    const [currentStatsResponse, prevStatsResponse] = await Promise.all([
      analyticsActions.getAggregateEntityStats(auth.site, values.analyticsKey, startTime, endTime, true),
      analyticsActions.getAggregateEntityStats(auth.site, values.analyticsKey, startTime - timeDifference, startTime, true),
    ]);

    const data = {
      requests: Analytics.countActivities(currentStatsResponse.data, 'Request', 'total'),
      prevRequests: Analytics.countActivities(prevStatsResponse.data, 'Request', 'total'),
      completedRequests: Analytics.countActivities(currentStatsResponse.data, 'RequestCompleted', 'unique'),
      prevCompletedRequests: Analytics.countActivities(prevStatsResponse.data, 'RequestCompleted', 'unique'),
      comments: Analytics.countActivities(currentStatsResponse.data, 'Comment', 'total'),
      prevComments: Analytics.countActivities(prevStatsResponse.data, 'Comment', 'total'),
      isLoading: false,
    };
    setAnalyticsData(data);
  };

  const isReadyToOpenCSV = () => {
    return !analyticsData.isLoading;
  };

  const getExportSource = () => {
    return [
      {
        startDate: moment(startTime + 1).format('D-MM-YYYY'),
        endDate: moment(endTime).format('D-MM-YYYY'),
        requests: analyticsData.requests,
        completedRequests: analyticsData.completedRequests,
        comments: analyticsData.comments,
      },
    ];
  };

  const csvPopup = () => {
    if (!isExportOpen) {
      return null;
    }
    const source = getExportSource();
    return (
      <Components.ExportCsvPopup
        onClose={() => {
          setIsExportOpen(false);
        }}
        columns={exportColumns}
        source={source}
        filename={`${values.analyticsKey}analytics_${source[0].startDate}_${source[0].endDate}.csv`}
      />
    );
  };

  return (
    <div className="dashboardSection">
      {csvPopup()}
      <div>
        <Components.Text type="h4" className="inlineBlock marginRight-40">
          {featureTitle}
        </Components.Text>
        <Components.Button
          inline
          buttonType="primaryAction"
          onClick={() => {
            if (!isReadyToOpenCSV()) return;
            setIsExportOpen(true);
          }}
          isActive={isReadyToOpenCSV()}
          leftIcon="file-code-o"
        >
          Export CSV
        </Components.Button>
      </div>
      <div className="analyticsSection dashboardSection_content">
        <Components.StatBox
          title={`${featureTitle} Requests`}
          icon={faWrench}
          value={analyticsData.requests}
          previousValue={analyticsData.prevRequests}
          prevText={prevText}
          viewGraphLink={`/chart?entity=${values.analyticsKey}&startTime=${startTime}&endTime=${endTime}&key=Request&countType=total&dayCount=${dayCount}`}
          isLoading={analyticsData.isLoading}
        />
        <Components.StatBox
          title={`Completed ${featureTitle} Requests`}
          icon={faCircleCheck}
          value={analyticsData.completedRequests}
          previousValue={analyticsData.prevCompletedRequests}
          prevText={prevText}
          viewGraphLink={`/chart?entity=${values.analyticsKey}&startTime=${startTime}&endTime=${endTime}&key=RequestCompleted&countType=unique&dayCount=${dayCount}`}
          isLoading={analyticsData.isLoading}
        />
        <Components.StatBox
          title={`${featureTitle} Comments`}
          icon={faComment}
          value={analyticsData.comments}
          previousValue={analyticsData.prevComments}
          prevText={prevText}
          viewGraphLink={`/chart?entity=${values.analyticsKey}&startTime=${startTime}&endTime=${endTime}&key=Comment&countType=total&dayCount=${dayCount}`}
          isLoading={analyticsData.isLoading}
        />
      </div>
    </div>
  );
};

const mapStateToProps = (state) => {
  const { auth } = state;
  return {
    auth,
    strings: (state.strings && state.strings.config) || {},
  };
};

const toExport = connect(mapStateToProps, {})(AnalyticsHub);
export { toExport as AnalyticsHub };
