import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import {
  createDashboardIsLoadingSelector,
  getCurrentVesselsStatusSorted,
  getRecentVesselsStatusSorted,
} from 'app/modules/dashboard/store/dashboard.selectors';
import datePipe from 'app/shared/pipes/date.pipe';
import { DashboardVesselListLabel } from 'app/modules/dashboard/components/dashboardVesselListLabel';
import HoverInfo from 'app/shared/components/hoverInfo/hoverInfo';
import { DashboardVesselListItem } from 'app/modules/dashboard/components/dashboardVesselListItem';
import { Spinner } from 'app/shared/components/spinner/spinner';
import { DASHBOARD } from 'app/modules/dashboard/store/dashboard.constants';
import { Headline } from 'app/shared/components/text/text';
import cx from 'classnames';

const getHoverTooltip = (isCurrentSelected) => <HoverInfo position={'top'}>
  {isCurrentSelected
    ? 'Earnings for the current voyage $/day'
    : 'Average pool earnings $/day'}
</HoverInfo>;

const getConsumptionTooltip = (recentDate: string | null = null) => (
  <HoverInfo position={'top'}>
    {!recentDate
      ? 'Total consumption from voyage start until today\'s date'
      : `Total consumption for ${datePipe.formatLongMonthWithYear(recentDate)}`}
  </HoverInfo>
);

const getCO2Tooltip = (recentDate: string | null = null) => (
  <HoverInfo position={'top'}>
    {!recentDate
      ? 'Total CO2 emission from voyage start until today\'s date'
      : `Total CO2 emission for ${datePipe.formatLongMonthWithYear(recentDate)}`}
  </HoverInfo>
);

const getVoyageDaysTooltip = () => (
  <HoverInfo position={'top'}>
    Number of days from voyage start until today&apos;s date
  </HoverInfo>
);

const getVesselListTooltip = () => <HoverInfo position={'top'}>
  The list below includes all vessels that have been active in our pools during the last month
</HoverInfo>;

export const DashboardVesselList = () => {
  const [ selectedRecentMonth, setSelectedRecentMonth ] = useState<string | null>(null);

  const recentVesselsStatus = useSelector(getRecentVesselsStatusSorted);
  const currentVesselsStatus = useSelector(getCurrentVesselsStatusSorted);
  const dashboardFetchCollectionSelector = [ DASHBOARD.FETCH_CURRENT_VESSELS_STATUS_SELECTOR ];
  const loadingStatus = useSelector(createDashboardIsLoadingSelector(dashboardFetchCollectionSelector));
  const listLabelClass = cx('c-dashboard-vessel-list__item', { 'c-dashboard-vessel-list__item--previous-period': selectedRecentMonth });
  const hooverTooltipsData = { 
    earnings: getHoverTooltip(!selectedRecentMonth),
    consumption: getConsumptionTooltip(selectedRecentMonth),
    co2Emission: getCO2Tooltip(selectedRecentMonth),
    voyageDays: getVoyageDaysTooltip(),
  };

  const unselectRecentMonth = () => {
    if (selectedRecentMonth) {
      setSelectedRecentMonth(null);
    }
  };

  const selectRecentMonth = (date) => {
    if (!selectedRecentMonth) {
      setSelectedRecentMonth(date);
    }
  };

  const recentMonths = recentVesselsStatus?.filter(item => item.date).map((item, index) => (
    <li key={index+1}>
      <button
        className={`c-option-button ${selectedRecentMonth === item.date ? 'c-option-button--active' : ''}`}
        onClick={() => selectRecentMonth(item.date)}
      >
        {datePipe.formatLongMonthWithYear(item.date)}
      </button>
    </li>
  ));

  return <div className="o-layout--full-width o-layout--vertical o-gutter-lg-top--big">
    <div className="c-dashboard-vessel-list__header o-page-layout__table-header o-page-layout__table-header--no-mobile o-page-layout--sticky-header">
      <div className="o-layout o-layout--wrap o-layout--space-between">
        <div className="o-layout o-layout--aligned o-gutter-top--medium u-margin-xl-bottom--jumbo">
          <Headline size="h2" extraClass="u-font--clear-spacings">Your Vessels</Headline>
        </div>
        <div className="u-margin-xl-bottom--jumbo o-gutter-top--medium">
          <ul className="c-dashboard-vessel-list__filters o-inline-list">
            <li key={0} className="u-margin-right--small">
              <button
                className={`c-option-button ${!selectedRecentMonth ? 'c-option-button--active' : ''}`}
                onClick={unselectRecentMonth}
              >
                Current Voyage
              </button>
            </li>
            { recentMonths }
          </ul>
        </div>
      </div>
      <div className="o-layout u-margin-top--small o-gutter-bottom--small">
        <div className={`${listLabelClass} c-dashboard-vessel-list__item--big`}>
          <DashboardVesselListLabel label="vessel" info={getVesselListTooltip()}/>
        </div>
        <div className={listLabelClass}>
          <DashboardVesselListLabel label="earnings" subLabel="$/day" info={hooverTooltipsData.earnings}/>
        </div>
        <div className={listLabelClass}>
          <DashboardVesselListLabel label="consumption" subLabel="MT" info={hooverTooltipsData.consumption} />
        </div>
        <div className={listLabelClass}>
          <DashboardVesselListLabel label="co2 emission" subLabel="MT" info={hooverTooltipsData.co2Emission}/>
        </div>
        { !selectedRecentMonth &&
          <div className={listLabelClass}>
            <DashboardVesselListLabel label="voyage days" info={hooverTooltipsData.voyageDays}/>
          </div>
        }
        <div className={listLabelClass}>
          <DashboardVesselListLabel label="vessel status"/>
        </div>
      </div>
    </div>
    <div className="c-dashboard-vessel-list">
      {!selectedRecentMonth && (loadingStatus ? <Spinner extraClass="u-margin-top--big" /> : currentVesselsStatus?.map(vesselStatus =>
        <DashboardVesselListItem 
          key={vesselStatus.vesselCode} 
          data={vesselStatus} 
          isCurrentVoyage 
          hoverTooltips={hooverTooltipsData}/>))
      }
      {selectedRecentMonth && 
        recentVesselsStatus.find(item => item.date === selectedRecentMonth)?.summaries?.map(vesselStatus =>
          <DashboardVesselListItem 
            key={vesselStatus.vesselCode} 
            data={vesselStatus} 
            hoverTooltips={hooverTooltipsData}/>)
      }
    </div>
  </div>;
};
