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

import { DocsTemplate } from '../../../.storybook'
import TimeframeComponent from './Timeframe'
import {
  historicalTimeframes,
  initialTimeframe,
} from '../../services/TimeframeServiceTyped'
import { toast } from '../Toast/Toast'

const meta: Meta<typeof TimeframeComponent> = {
  title: 'Components/Timeframe',
  component: TimeframeComponent,
  parameters: {
    docs: {
      page: () => (
        <DocsTemplate
          description={
            <span>
              The <code>Timeframe</code> component is a sophisticated date range
              selector that provides multiple ways to select and display time
              periods. It's designed to handle various timeframe selection
              needs, from simple date ranges to complex comparison periods and
              aggregations.
            </span>
          }
          infoBullets={[
            'Supports multiple timeframe types: Current, Historical, Quarterly/Yearly, and Previous',
            'Offers custom date range selection with a date picker',
            'Includes comparison date range functionality for analyzing trends',
            'Provides timeframe aggregations for data analysis',
            'Features mobile-optimized layouts and interactions',
            'Supports disabled states and custom configurations',
            'Includes alert functionality to display selected date ranges',
          ]}
        />
      ),
    },
  },
}

export default meta

type Story = StoryObj<typeof TimeframeComponent>

// Base template with common functionality
const Timeframe = (args) => {
  const [timeframe, setTimeframe] = useState(initialTimeframe)

  const update = (
    calloutType: string,
    startDate: moment.Moment,
    endDate: moment.Moment,
    timeframe: {
      type: string
      display: string
      value: number
      timeValue: string
    },
  ) => {
    setTimeframe(timeframe)
    if (startDate && endDate) {
      toast({
        message: (
          <div>
            <span>Start Date: {moment(startDate).format('L')}</span>
            <br />
            <span>End Date: {moment(endDate).format('L')}</span>
            <br />
          </div>
        ),
        type: 'info',
      })
    }
  }

  return (
    <div style={{ width: '400px', padding: '20px' }}>
      <TimeframeComponent {...args} timeframe={timeframe} callout={update} />
    </div>
  )
}

// Basic Timeframe with all sections
export const Basic: Story = {
  render: (args) => <Timeframe {...args} />,
  args: {
    historicalTimeframes: historicalTimeframes,
    currentTimeframe: true,
    previousTimeframe: true,
    quarterlyTimeframe: true,
    hideCustomDateSearch: false,
  },
}

// Timeframe with Toast
export const WithToast: Story = {
  render: (args) => <Timeframe {...args} />,
  args: {
    ...Basic.args,
    alertProps: {
      text: 'Select a date range to view data',
      type: 'info' as const,
      selectedDatesCallout: ({
        startDate,
        endDate,
        comparisonStartDate,
        comparisonEndDate,
      }) => {
        const message =
          comparisonStartDate && comparisonEndDate
            ? `Selected range: ${moment(startDate).format('L')} to ${moment(endDate).format('L')}\nComparison range: ${moment(comparisonStartDate).format('L')} to ${moment(comparisonEndDate).format('L')}`
            : `Selected range: ${moment(startDate).format('L')} to ${moment(endDate).format('L')}`

        toast({
          message,
          type: 'info',
        })
      },
    },
  },
}

// Timeframe with Comparison Dates
export const WithComparisonDates: Story = {
  render: (args) => <Timeframe {...args} />,
  args: {
    ...Basic.args,
    comparisonDateRange: {
      firstRange_startDate: moment().subtract(1, 'year'),
      firstRange_endDate: moment(),
      secondRange_startDate: moment().subtract(2, 'year'),
      secondRange_endDate: moment().subtract(1, 'year'),
    },
    getComparisonDateRange: true,
  },
}

// Timeframe with custom labels
export const WithCustomLabels: Story = {
  render: (args) => <Timeframe {...args} />,
  args: {
    ...Basic.args,
    comparisonDateRange: {
      firstRange_startDate: moment().subtract(1, 'year'),
      firstRange_endDate: moment(),
      secondRange_startDate: moment().subtract(2, 'year'),
      secondRange_endDate: moment().subtract(1, 'year'),
    },
    getComparisonDateRange: true,
    firstRangeLabel: 'Primary Range',
    secondRangeLabel: 'Secondary Range',
  },
}

// Disabled Timeframe
export const Disabled: Story = {
  render: (args) => <Timeframe {...args} />,
  args: {
    ...Basic.args,
    disableTimeFrameFilter: true,
    disabledTimeframeOptions: {
      current: ['day', 'week'],
      historical: ['30days', '3months'],
      quarterly: ['q1', 'q2'],
    },
  },
}

// Custom Timeframe
export const Custom: Story = {
  render: (args) => <Timeframe {...args} />,
  args: {
    ...Basic.args,
    hideCustomDateSearch: false,
    startDate: moment().subtract(1, 'month').format('YYYY-MM-DD'),
    endDate: moment().format('YYYY-MM-DD'),
  },
}

// Minimal Timeframe
export const Minimal: Story = {
  render: (args) => <Timeframe {...args} />,
  args: {
    historicalTimeframes: historicalTimeframes,
    currentTimeframe: true,
    previousTimeframe: false,
    quarterlyTimeframe: false,
    hideCustomDateSearch: true,
  },
}

// Timeframe without Comparison Datepicker
export const withoutComparisonDatepicker: Story = {
  render: (args) => <Timeframe {...args} />,
  args: {
    ...Basic.args,
    showHistoricTimeFrameDateRange: false,
  },
}
