'use client'

import React, { createContext, useContext, useState, useEffect, Suspense } from 'react'
import { useRouter, useSearchParams, usePathname } from 'next/navigation'

interface AnalysisYearContextType {
  selectedYear: number
  setSelectedYear: (year: number) => void
  availableYears: number[]
}

const AnalysisYearContext = createContext<AnalysisYearContextType | undefined>(undefined)

function AnalysisYearProviderInner({ children }: { children: React.ReactNode }) {
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()

  // 사용 가능한 분석 연도 목록 (현재 연도부터 과거 5년)
  const currentYear = new Date().getFullYear()
  const availableYears = Array.from({ length: 6 }, (_, i) => currentYear - i)

  // URL 파라미터에서 연도 가져오기, 없으면 현재 연도 사용
  const yearFromUrl = searchParams.get('year')
  const initialYear = yearFromUrl && !isNaN(Number(yearFromUrl))
    ? Number(yearFromUrl)
    : currentYear

  const [selectedYear, setSelectedYearState] = useState<number>(initialYear)

  // URL 파라미터와 동기화
  useEffect(() => {
    const yearParam = searchParams.get('year')
    if (yearParam && !isNaN(Number(yearParam))) {
      const year = Number(yearParam)
      if (availableYears.includes(year)) {
        setSelectedYearState(year)
      }
    }
  }, [searchParams, availableYears])

  const setSelectedYear = (year: number) => {
    setSelectedYearState(year)

    // URL 파라미터 업데이트
    const params = new URLSearchParams(searchParams.toString())
    params.set('year', year.toString())
    router.push(`${pathname}?${params.toString()}`)
  }

  return (
    <AnalysisYearContext.Provider value={{ selectedYear, setSelectedYear, availableYears }}>
      {children}
    </AnalysisYearContext.Provider>
  )
}

export function AnalysisYearProvider({ children }: { children: React.ReactNode }) {
  return (
    <Suspense fallback={null}>
      <AnalysisYearProviderInner>{children}</AnalysisYearProviderInner>
    </Suspense>
  )
}

export function useAnalysisYear() {
  const context = useContext(AnalysisYearContext)
  if (context === undefined) {
    throw new Error('useAnalysisYear must be used within an AnalysisYearProvider')
  }
  return context
}
