import { type Meta, type StoryObj } from '@storybook/react-vite'
import moment from 'moment'
import React, { useState } from 'react'

import { DocsTemplate } from '../../../.storybook'
import {
  type CompareWith,
  type TimeframeType,
} from '../../components/HeaderMetric/HeaderMetricHelpers'
import { getComparisonDates } from '../../services/DateHelpers'
import {
  historicalTimeframes,
  initialTimeframe,
} from '../../services/TimeframeServiceTyped'
import Picker from '../../components/Picker/Picker'
import Timeframe from '../../components/TimeframeFilter/Timeframe'
import { toast } from '../../components/Toast/Toast'

const options: {
  id: number
  text: string
  value: CompareWith
}[] = [
  {
    id: 1,
    text: 'Previous Period',
    value: 'previous_period',
  },
  {
    id: 2,
    text: 'Previous Year',
    value: 'previous_year',
  },
]

const HandleComparisonDates = (args) => {
  const [timeframe, setTimeframe] = useState(initialTimeframe)
  const [compareWith, setCompareWith] = useState(options[0])

  const updateCompareWith = (value) => {
    const activeOption = options.find((item) => item.value === value)
    setCompareWith(activeOption || options[0])
  }

  const update = (
    _: string,
    startDate: moment.Moment,
    endDate: moment.Moment,
    timeframe: typeof initialTimeframe,
  ) => {
    setTimeframe(timeframe)
    const comparisonDates = getComparisonDates({
      startDate: startDate.format('YYYY-MM-DD'),
      endDate: endDate.format('YYYY-MM-DD'),
      timeframe: timeframe as TimeframeType,
      compareWith: compareWith.value,
    })

    toast({
      message: (
        <div>
          <span>Start Date: {startDate.format('L')}</span>
          <br />
          <span>End Date: {endDate.format('L')}</span>
          <br />
          <span>
            Comparison Start Date:{' '}
            {moment(comparisonDates?.startDate).format('L')}
          </span>
          <br />
          <span>
            Comparison End Date: {moment(comparisonDates?.endDate).format('L')}
          </span>
          <br />
        </div>
      ),
      type: 'info',
      config: {
        autoClose: false,
      },
    })
  }

  return (
    <>
      <Timeframe {...args} timeframe={timeframe} callout={update} />
      <Picker
        options={options}
        state={compareWith}
        stateName='value'
        callout={(_, value) => updateCompareWith(value)}
      />
    </>
  )
}

type Story = StoryObj<typeof HandleComparisonDates>

const Template: Story = {
  render: ({ ...args }) => {
    return <HandleComparisonDates {...args} />
  },
}

export const Example = {
  ...Template,
  args: {
    historicalTimeframes: historicalTimeframes,
    currentTimeframe: true,
    previousTimeframe: true,
    quarterlyTimeframe: true,
    hideCustomDateSearch: true,
  },
}

const meta: Meta<typeof HandleComparisonDates> = {
  title: 'Helper Functions/getComparisonDates',
  component: HandleComparisonDates,
  parameters: {
    docs: {
      page: () => (
        <>
          <DocsTemplate
            description={`A function used to return comparison dates based on the current timeframe and comparison selection.`}
            infoBullets={[
              <span key='first-line'>
                <code>getComparisonDates</code> is used to provide comparison
                dates. It takes in the following arguments:
                <ul>
                  <li>
                    <code>startDate</code>: The start date of the selected
                    timeframe.
                  </li>
                  <li>
                    <code>endDate</code>: The end date of the selected
                    timeframe.
                  </li>
                  <li>
                    <code>timeframe</code>: The timeframe object.
                  </li>
                  <li>
                    <code>compareWith</code>: The comparison selection. Either{' '}
                    <code>previous_period</code> or <code>previous_year</code>.
                  </li>
                  <li>
                    <code>hasNoCurrentMonthData</code>: A boolean indicating if
                    the current month has no data.
                  </li>
                </ul>
              </span>,
            ]}
          />
        </>
      ),
    },
  },
}

export default meta
