import React from 'react'

import { type AlertProps } from '../Alerts/Alert'
import type {
  CalloutType,
  ComparisonDateRangeProps,
  CustomAggregationsProps,
  DisabledTimeframeOptionsProps,
  TimeframeProps,
} from './TimeframesType'
import styles from './_timeframe-filter.module.scss'
import type { SideDrawerBase } from '../SideDrawer/SideDrawer'
import { c } from '../../translations/LibraryTranslationService'

const HistoricalTimeframe = React.lazy(() =>
  import(
    /* webpackChunkName: "historicalTimeframe" */ './TimeframeTypes/HistoricalTimeframe'
  ).then((mod) => ({ default: mod.HistoricalTimeframe })),
)
const CurrentTimeframe = React.lazy(() =>
  import(
    /* webpackChunkName: "currentTimeframe" */ './TimeframeTypes/CurrentTimeframe'
  ).then((mod) => ({ default: mod.CurrentTimeframe })),
)
const QuarterlyTimeframe = React.lazy(() =>
  import(
    /* webpackChunkName: "quarterlyTimeframe" */ './TimeframeTypes/QuarterlyTimeframe'
  ).then((mod) => ({ default: mod.QuarterlyTimeframe })),
)
const PreviousTimeframe = React.lazy(() =>
  import(
    /* webpackChunkName: "previousTimeframe" */ './TimeframeTypes/PreviousTimeframe'
  ).then((mod) => ({ default: mod.PreviousTimeframe })),
)
const Aggregations = React.lazy(
  () =>
    import(
      /* webpackChunkName: "timeframeAggregations" */ './TimeframeTypes/Aggregations'
    ),
)

type AlertCalloutType = {
  startDate: string
  endDate: string
  comparisonStartDate: string
  comparisonEndDate: string
}

export type AlertPropsWithDates = AlertProps & {
  selectedDatesCallout?: ({
    startDate,
    endDate,
    comparisonStartDate,
    comparisonEndDate,
  }: AlertCalloutType) => void
}

export type TimeframeFilterBodyProps = {
  /** Callout for each user action */
  callout: (
    calloutType: CalloutType,
    startDate: moment.Moment,
    endDate: moment.Moment,
    timeframe: TimeframeProps,
  ) => void
  timeframe: TimeframeProps
  historicalTimeframes?: Array<TimeframeProps>
  /** Boolean: show the current timeframe options */
  currentTimeframe?: boolean
  /** Boolean: show the previous timeframe options */
  previousTimeframe?: boolean
  /** Boolean: show the quarterly timeframe options */
  quarterlyTimeframe?: boolean
  /** Boolean: show the custom date calendar options */
  hideCustomDateSearch?: boolean
  closeMenu?: () => void
  useTimeframeAggregations?: boolean
  customAggregations?: CustomAggregationsProps
  startDate?: string
  endDate?: string
  disableTimeFrameFilter?: boolean
  showHistoricTimeFrameDateRange?: boolean
  showHistoricTimeFrameDateRangeOnMobile?: boolean
  comparisonDateRange?: ComparisonDateRangeProps
  getComparisonDateRange?: boolean
  disabledTimeframeOptions?: DisabledTimeframeOptionsProps
  updateToValidFilterState?: (
    calloutType: CalloutType,
    validOptions: unknown,
  ) => void
  /** Passes any optional SideDrawer props to the ComparisonDatePicker SideDrawer */
  cdpSideDrawerProps?: Omit<
    SideDrawerBase,
    'children' | 'isOpen' | 'closeCallout'
  >
  /** Boolean: Show the new trailing timeframe options */
  trailingTimeframe?: boolean
  alertProps?: AlertPropsWithDates
  /** Current path from the router */
  currentPath?: string
  /** Optional prop to add a test id to the Timeframe for QA testing */
  qaTestId?: string
  firstRangeLabel?: string
  secondRangeLabel?: string
}

const Timeframe = ({
  callout,
  historicalTimeframes,
  timeframe,
  // ToDo: Clean up this check once we start supporting new timeframe options across all Predict modules and Shelf app
  // Hence we have not updated storybook for this change
  trailingTimeframe = false,
  currentTimeframe,
  previousTimeframe = false,
  quarterlyTimeframe,
  closeMenu,
  useTimeframeAggregations = false,
  customAggregations,
  startDate,
  endDate,
  disableTimeFrameFilter = false,
  showHistoricTimeFrameDateRange = true,
  showHistoricTimeFrameDateRangeOnMobile = false, // for mobile
  comparisonDateRange,
  getComparisonDateRange,
  disabledTimeframeOptions = undefined,
  updateToValidFilterState = () => null,
  cdpSideDrawerProps,
  alertProps,
  currentPath,
  qaTestId = 'timeframe',
  firstRangeLabel,
  secondRangeLabel,
}: TimeframeFilterBodyProps) => {
  return (
    <React.Suspense fallback={<div>Loading...</div>}>
      <div
        className={`${styles.timeframeContainer} ${
          disableTimeFrameFilter ? styles.disableTimeframeColumn : ''
        }`}
        style={{
          justifyContent: useTimeframeAggregations ? 'space-between' : 'start',
        }}
        qa-test-id={qaTestId}
      >
        <div>
          {currentTimeframe ? (
            <>
              <div
                className={`${styles.timeframeSectionHeader} ${
                  timeframe.type === 'current' ? styles.active : ''
                }`}
                data-timeframe-section-header='timeframe-body'
              >
                {c('current')}
              </div>
              <CurrentTimeframe
                callout={callout}
                timeframe={timeframe}
                closeMenu={closeMenu}
                useTimeframeAggregations={useTimeframeAggregations}
                customAggregations={customAggregations?.current}
                disabledTimeframeOptions={disabledTimeframeOptions?.current}
              />
            </>
          ) : null}
          {previousTimeframe ? (
            <>
              <div
                className={`${styles.timeframeSectionHeader} ${
                  timeframe.type === 'previous' ? styles.active : ''
                }`}
                data-timeframe-section-header='timeframe-body'
              >
                {c('previous')}
              </div>
              <PreviousTimeframe
                callout={callout}
                timeframe={timeframe}
                closeMenu={() => closeMenu?.()}
                useTimeframeAggregations={useTimeframeAggregations}
                customAggregations={customAggregations?.previous ?? {}}
                disabledTimeframeOptions={
                  disabledTimeframeOptions?.previous ?? []
                }
              />
            </>
          ) : null}
          {currentTimeframe || quarterlyTimeframe ? (
            <div
              className={`${styles.timeframeSectionHeader} ${
                timeframe.type === 'historical' || timeframe.type === 'trailing'
                  ? styles.active
                  : ''
              }`}
              data-timeframe-section-header='timeframe-body'
            >
              {trailingTimeframe ? c('trailing') : c('historical')}
            </div>
          ) : null}
          <HistoricalTimeframe
            alertProps={alertProps}
            callout={callout}
            timeframes={historicalTimeframes ?? []}
            timeframe={timeframe}
            closeMenu={closeMenu}
            useTimeframeAggregations={useTimeframeAggregations}
            showHistoricTimeFrameDateRange={showHistoricTimeFrameDateRange}
            comparisonDateRange={comparisonDateRange}
            getComparisonDateRange={getComparisonDateRange}
            customAggregations={
              trailingTimeframe
                ? customAggregations?.trailing
                : customAggregations?.historical
            }
            disabledTimeframeOptions={
              trailingTimeframe
                ? disabledTimeframeOptions?.trailing
                : disabledTimeframeOptions?.historical
            }
            showHistoricTimeFrameDateRangeOnMobile={
              showHistoricTimeFrameDateRangeOnMobile
            }
            cdpSideDrawerProps={cdpSideDrawerProps}
            trailingTimeframe={trailingTimeframe}
            firstRangeLabel={firstRangeLabel}
            secondRangeLabel={secondRangeLabel}
          />
          {quarterlyTimeframe ? (
            <>
              <div
                className={`${styles.timeframeSectionHeader} ${
                  timeframe.type === 'quarterly' ? styles.active : ''
                }`}
                data-timeframe-section-header='timeframe-body'
              >
                {c('quarterly/yearly')}
              </div>
              <QuarterlyTimeframe
                callout={callout}
                timeframe={timeframe}
                closeMenu={closeMenu}
                useTimeframeAggregations={useTimeframeAggregations}
                customAggregations={customAggregations}
                disabledTimeframeOptions={disabledTimeframeOptions?.quarterly}
              />
            </>
          ) : null}

          {showHistoricTimeFrameDateRangeOnMobile ? (
            <>
              <div
                className={`${styles.timeframeSectionHeader} ${
                  timeframe.type === 'historical' ||
                  timeframe.type === 'trailing'
                    ? styles.active
                    : ''
                }`}
                data-timeframe-section-header='timeframe-body-historical'
              >
                {c('customDate')}
              </div>

              <HistoricalTimeframe
                alertProps={alertProps}
                callout={callout}
                timeframes={[]}
                timeframe={timeframe}
                closeMenu={closeMenu}
                useTimeframeAggregations={useTimeframeAggregations}
                showHistoricTimeFrameDateRange={true}
                comparisonDateRange={comparisonDateRange}
                getComparisonDateRange={getComparisonDateRange}
                customAggregations={
                  trailingTimeframe
                    ? customAggregations?.trailing
                    : customAggregations?.historical
                }
                disabledTimeframeOptions={
                  trailingTimeframe
                    ? disabledTimeframeOptions?.trailing
                    : disabledTimeframeOptions?.historical
                }
                showHistoricTimeFrameDateRangeOnMobile={
                  showHistoricTimeFrameDateRangeOnMobile
                }
                cdpSideDrawerProps={cdpSideDrawerProps}
                trailingTimeframe={trailingTimeframe}
                firstRangeLabel={firstRangeLabel}
                secondRangeLabel={secondRangeLabel}
              />
            </>
          ) : null}
        </div>
        {useTimeframeAggregations ? (
          <Aggregations
            timeframe={timeframe}
            callout={callout}
            startDate={startDate}
            endDate={endDate}
            customAggregations={customAggregations}
            updateToValidFilterState={updateToValidFilterState}
            trailingTimeframe={trailingTimeframe}
            currentPath={currentPath}
          />
        ) : null}
      </div>
    </React.Suspense>
  )
}

export default Timeframe
