import { createContext, useContext, useState, useMemo } from 'react'

export type Preset = '4w' | '3m' | '6m' | '1y' | 'all' | 'custom'

interface TimeframeCtx {
  preset: Preset
  dateFrom: string | undefined
  dateTo: string | undefined
  customFrom: string
  customTo: string
  setPreset: (p: Preset) => void
  setCustomFrom: (v: string) => void
  setCustomTo: (v: string) => void
}

const Ctx = createContext<TimeframeCtx | null>(null)

export function useDashboardTimeframe() {
  const ctx = useContext(Ctx)
  if (!ctx) throw new Error('useDashboardTimeframe must be inside DashboardTimeframeProvider')
  return ctx
}

function toISO(d: Date) {
  return d.toISOString().slice(0, 10)
}

function presetDates(p: Preset): { from: string | undefined; to: string | undefined } {
  const now = new Date()
  const to = toISO(now)
  switch (p) {
    case '4w': { const d = new Date(now); d.setDate(d.getDate() - 28); return { from: toISO(d), to } }
    case '3m': { const d = new Date(now); d.setMonth(d.getMonth() - 3); return { from: toISO(d), to } }
    case '6m': { const d = new Date(now); d.setMonth(d.getMonth() - 6); return { from: toISO(d), to } }
    case '1y': { const d = new Date(now); d.setFullYear(d.getFullYear() - 1); return { from: toISO(d), to } }
    case 'all': return { from: '2000-01-01', to }
    case 'custom': return { from: undefined, to: undefined }
  }
}

export function DashboardTimeframeProvider({ children }: { children: React.ReactNode }) {
  const [preset, setPresetState] = useState<Preset>('6m')
  const [customFrom, setCustomFrom] = useState('')
  const [customTo, setCustomTo] = useState('')

  function setPreset(p: Preset) {
    setPresetState(p)
    if (p !== 'custom') {
      setCustomFrom('')
      setCustomTo('')
    }
  }

  const { dateFrom, dateTo } = useMemo(() => {
    if (preset === 'custom') {
      return { dateFrom: customFrom || undefined, dateTo: customTo || undefined }
    }
    const r = presetDates(preset)
    return { dateFrom: r.from, dateTo: r.to }
  }, [preset, customFrom, customTo])

  return (
    <Ctx.Provider value={{ preset, dateFrom, dateTo, customFrom, customTo, setPreset, setCustomFrom, setCustomTo }}>
      {children}
    </Ctx.Provider>
  )
}
