import { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from 'react'
import { computePresetRange } from '../utils/timePresets'

export interface TimeRange {
  start: Date
  end: Date
  preset: string | null
}

export type ExchangeStatus = 'completed' | 'failed' | 'running' | 'warning'

interface GlobalFilterContextValue {
  timeRange: TimeRange
  setTimeRange: (range: TimeRange) => void
  refreshTimeRange: () => void
  statusFilters: Set<ExchangeStatus>
  toggleStatus: (status: ExchangeStatus) => void
  clearStatusFilters: () => void
  isInTimeRange: (timestamp: Date) => boolean
  autoRefresh: boolean
  setAutoRefresh: (enabled: boolean) => void
}

const GlobalFilterContext = createContext<GlobalFilterContextValue | null>(null)

const DEFAULT_PRESET = 'last-1h'

function getDefaultTimeRange(): TimeRange {
  const { start, end } = computePresetRange(DEFAULT_PRESET)
  return { start, end, preset: DEFAULT_PRESET }
}

function getInitialAutoRefresh(): boolean {
  try {
    const stored = localStorage.getItem('cameleer:auto-refresh')
    return stored === null ? true : stored === 'true'
  } catch { return true }
}

export function GlobalFilterProvider({ children }: { children: ReactNode }) {
  const [timeRange, setTimeRangeState] = useState<TimeRange>(getDefaultTimeRange)
  const [statusFilters, setStatusFilters] = useState<Set<ExchangeStatus>>(new Set())
  const [autoRefresh, setAutoRefreshState] = useState<boolean>(getInitialAutoRefresh)

  const setTimeRange = useCallback((range: TimeRange) => {
    setTimeRangeState(range)
  }, [])

  const toggleStatus = useCallback((status: ExchangeStatus) => {
    setStatusFilters((prev) => {
      const next = new Set(prev)
      if (next.has(status)) {
        next.delete(status)
      } else {
        next.add(status)
      }
      return next
    })
  }, [])

  const clearStatusFilters = useCallback(() => {
    setStatusFilters(new Set())
  }, [])

  const setAutoRefresh = useCallback((enabled: boolean) => {
    setAutoRefreshState(enabled)
    try { localStorage.setItem('cameleer:auto-refresh', String(enabled)) } catch {}
  }, [])

  // Keep the time range sliding forward when a preset is active and live
  useEffect(() => {
    if (!autoRefresh || !timeRange.preset) return
    const id = setInterval(() => {
      const { start, end } = computePresetRange(timeRange.preset!)
      setTimeRangeState({ start, end, preset: timeRange.preset })
    }, 10_000)
    return () => clearInterval(id)
  }, [autoRefresh, timeRange.preset])

  // Recompute time range from preset on demand (for manual refresh in PAUSED mode)
  const refreshTimeRange = useCallback(() => {
    if (timeRange.preset) {
      const { start, end } = computePresetRange(timeRange.preset)
      setTimeRangeState({ start, end, preset: timeRange.preset })
    }
  }, [timeRange.preset])

  const isInTimeRange = useCallback(
    (timestamp: Date) => {
      if (timeRange.preset) {
        // Recompute from now so the window stays fresh
        const { start } = computePresetRange(timeRange.preset)
        return timestamp >= start
      }
      return timestamp >= timeRange.start && timestamp <= timeRange.end
    },
    [timeRange],
  )

  return (
    <GlobalFilterContext.Provider
      value={{ timeRange, setTimeRange, refreshTimeRange, statusFilters, toggleStatus, clearStatusFilters, isInTimeRange, autoRefresh, setAutoRefresh }}
    >
      {children}
    </GlobalFilterContext.Provider>
  )
}

export function useGlobalFilters(): GlobalFilterContextValue {
  const ctx = useContext(GlobalFilterContext)
  if (!ctx) throw new Error('useGlobalFilters must be used within GlobalFilterProvider')
  return ctx
}
