import { useState } from 'react'
import styles from './DateRangePicker.module.css'
import { DateTimePicker } from '../DateTimePicker/DateTimePicker'
import { FilterPill } from '../FilterPill/FilterPill'
import { DEFAULT_PRESETS, computePresetRange, type DateRange, type Preset } from '../../utils/timePresets'

interface DateRangePickerProps {
  value: DateRange
  onChange: (range: DateRange) => void
  presets?: Preset[]
  className?: string
}

export function DateRangePicker({
  value,
  onChange,
  presets = DEFAULT_PRESETS,
  className,
}: DateRangePickerProps) {
  const [activePreset, setActivePreset] = useState<string | null>(null)

  function handlePreset(preset: Preset) {
    if (preset.value === 'custom') {
      setActivePreset('custom')
      return
    }
    const range = computePresetRange(preset.value)
    setActivePreset(preset.value)
    onChange(range)
  }

  function handleStartChange(date: Date | null) {
    if (!date) return
    setActivePreset(null)
    onChange({ ...value, start: date })
  }

  function handleEndChange(date: Date | null) {
    if (!date) return
    setActivePreset(null)
    onChange({ ...value, end: date })
  }

  return (
    <div className={`${styles.root} ${className ?? ''}`}>
      <div className={styles.presets}>
        {presets.map((preset) => (
          <FilterPill
            key={preset.value}
            label={preset.label}
            active={activePreset === preset.value}
            onClick={() => handlePreset(preset)}
          />
        ))}
      </div>
      <div className={styles.inputs}>
        <DateTimePicker
          label="From"
          value={value.start}
          onChange={handleStartChange}
        />
        <span className={styles.separator}>→</span>
        <DateTimePicker
          label="To"
          value={value.end}
          onChange={handleEndChange}
        />
      </div>
    </div>
  )
}
