import { useState, useEffect } from 'react'
import styles from './TimeRangeDropdown.module.css'
import { SegmentedTabs } from '../../composites/SegmentedTabs/SegmentedTabs'
import { DateTimePicker } from '../DateTimePicker/DateTimePicker'
import { computePresetRange } from '../../utils/timePresets'
import type { TimeRange } from '../../providers/GlobalFilterProvider'

const PRESETS = [
  { value: 'last-1h', label: '1h' },
  { value: 'last-3h', label: '3h' },
  { value: 'last-6h', label: '6h' },
  { value: 'today', label: 'Today' },
  { value: 'last-24h', label: '24h' },
  { value: 'last-7d', label: '7d' },
]

const CUSTOM_VALUE = '__custom__'

interface TimeRangeDropdownProps {
  value: TimeRange
  onChange: (range: TimeRange) => void
  className?: string
}

export function TimeRangeDropdown({ value, onChange, className }: TimeRangeDropdownProps) {
  const [customFrom, setCustomFrom] = useState<Date>(value.start)
  const [customTo, setCustomTo] = useState<Date>(value.end)
  const [toIsSet, setToIsSet] = useState(false)

  const isCustom = value.preset === null || value.preset === 'custom'
  const activeValue = isCustom ? CUSTOM_VALUE : (value.preset ?? 'last-1h')

  // Sync local state when value changes from presets
  useEffect(() => {
    setCustomFrom(value.start)
    setCustomTo(value.end)
  }, [value.start, value.end])

  function handleTabChange(tabValue: string) {
    if (tabValue === CUSTOM_VALUE) return
    setToIsSet(false)
    const range = computePresetRange(tabValue)
    onChange({ ...range, preset: tabValue })
  }

  function handleFromChange(d: Date | null) {
    if (!d) return
    setCustomFrom(d)
    // Only set preset to null; keep to-date as "now" if not explicitly set
    if (toIsSet) {
      onChange({ start: d, end: customTo, preset: null })
    } else {
      onChange({ start: d, end: new Date(), preset: null })
    }
  }

  function handleToChange(d: Date | null) {
    if (!d) return
    setCustomTo(d)
    setToIsSet(true)
    onChange({ start: customFrom, end: d, preset: null })
  }

  // Show "now" when to-date is not explicitly set
  const showNow = !isCustom || !toIsSet

  const rangeContent = (
    <div className={styles.rangeRow}>
      <DateTimePicker
        value={isCustom ? customFrom : value.start}
        onChange={handleFromChange}
      />
      <span className={styles.rangeSep}>–</span>
      {showNow ? (
        <DateTimePicker
          value={undefined}
          onChange={handleToChange}
          placeholder="now"
        />
      ) : (
        <DateTimePicker
          value={customTo}
          onChange={handleToChange}
        />
      )}
    </div>
  )

  return (
    <div className={className}>
      <SegmentedTabs
        tabs={PRESETS}
        active={activeValue}
        onChange={handleTabChange}
        trailing={rangeContent}
        trailingValue={CUSTOM_VALUE}
      />
    </div>
  )
}
