'use client'

import {
  createContext,
  useContext,
  useState,
  useEffect,
  useCallback,
  type ReactNode,
} from 'react'
import { useRouter, useSearchParams, usePathname } from 'next/navigation'

export type Edition = {
  id: string
  name: string
  year: number
  status: 'DRAFT' | 'ACTIVE' | 'ARCHIVED'
}

type EditionContextType = {
  currentEdition: Edition | null
  editions: Edition[]
  setCurrentEdition: (id: string) => void
  isLoading: boolean
}

const EditionContext = createContext<EditionContextType | undefined>(undefined)

const STORAGE_KEY = 'mopc-selected-edition'

export function EditionProvider({
  children,
  editions: initialEditions,
}: {
  children: ReactNode
  editions: Edition[]
}) {
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const [editions] = useState<Edition[]>(initialEditions)
  const [currentEdition, setCurrentEditionState] = useState<Edition | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  // Initialize edition from URL param, localStorage, or default to most recent active
  useEffect(() => {
    const editionFromUrl = searchParams.get('edition')
    const storedEditionId = typeof window !== 'undefined'
      ? localStorage.getItem(STORAGE_KEY)
      : null

    let selectedEdition: Edition | null = null

    // Priority: URL param > localStorage > most recent active > first in list
    if (editionFromUrl) {
      selectedEdition = editions.find(e => e.id === editionFromUrl) || null
    }

    if (!selectedEdition && storedEditionId) {
      selectedEdition = editions.find(e => e.id === storedEditionId) || null
    }

    if (!selectedEdition) {
      // Default to most recent active edition, or just the first one
      selectedEdition = editions.find(e => e.status === 'ACTIVE') || editions[0] || null
    }

    if (selectedEdition) {
      setCurrentEditionState(selectedEdition)
      if (typeof window !== 'undefined') {
        localStorage.setItem(STORAGE_KEY, selectedEdition.id)
      }
    }

    setIsLoading(false)
  }, [editions, searchParams])

  const setCurrentEdition = useCallback((id: string) => {
    const edition = editions.find(e => e.id === id)
    if (edition) {
      setCurrentEditionState(edition)
      if (typeof window !== 'undefined') {
        localStorage.setItem(STORAGE_KEY, id)
      }

      // Update URL with edition param using window.history to avoid type issues
      const params = new URLSearchParams(searchParams.toString())
      params.set('edition', id)
      const newUrl = `${pathname}?${params.toString()}`
      window.history.pushState({}, '', newUrl)
      router.refresh()
    }
  }, [editions, router, pathname, searchParams])

  return (
    <EditionContext.Provider
      value={{
        currentEdition,
        editions,
        setCurrentEdition,
        isLoading,
      }}
    >
      {children}
    </EditionContext.Provider>
  )
}

export function useEdition() {
  const context = useContext(EditionContext)
  if (context === undefined) {
    throw new Error('useEdition must be used within an EditionProvider')
  }
  return context
}
