"use client"

import { useState, useEffect, useCallback } from "react"
import { usePathname, useSearchParams, useRouter } from "next/navigation"
import { DateRange } from "react-day-picker"

interface FilterState {
    searchQuery?: string
    statusFilter?: string
    dateRange?: DateRange
    page?: number
    itemsPerPage?: number
    sortColumn?: string
    sortDirection?: "asc" | "desc"
}

interface UseFilterStateOptions {
    /** Unique key for this page's filter state */
    storageKey: string
    /** Initialize from URL params on mount */
    syncWithUrl?: boolean
    /** Default values */
    defaults?: Partial<FilterState>
}

/**
 * useFilterState - Persist filter state across navigation
 * Uses sessionStorage to remember filters per page
 */
export function useFilterState({
    storageKey,
    syncWithUrl = false,
    defaults = {}
}: UseFilterStateOptions) {
    const pathname = usePathname()
    const searchParams = useSearchParams()
    const router = useRouter()

    const fullKey = `filterState:${storageKey}`

    // Initialize state from sessionStorage or URL params
    const getInitialState = (): FilterState => {
        if (typeof window === "undefined") return defaults

        // First try URL params if syncWithUrl is enabled
        if (syncWithUrl && searchParams) {
            const urlState: FilterState = {}
            const status = searchParams.get("status")
            const search = searchParams.get("search")
            const page = searchParams.get("page")

            if (status) urlState.statusFilter = status
            if (search) urlState.searchQuery = search
            if (page) urlState.page = parseInt(page)

            if (Object.keys(urlState).length > 0) {
                return { ...defaults, ...urlState }
            }
        }

        // Then try sessionStorage
        try {
            const stored = sessionStorage.getItem(fullKey)
            if (stored) {
                const parsed = JSON.parse(stored)
                // Restore dateRange as Date objects
                if (parsed.dateRange) {
                    if (parsed.dateRange.from) parsed.dateRange.from = new Date(parsed.dateRange.from)
                    if (parsed.dateRange.to) parsed.dateRange.to = new Date(parsed.dateRange.to)
                }
                return { ...defaults, ...parsed }
            }
        } catch (e) {
            console.warn("Failed to load filter state from storage:", e)
        }

        return defaults
    }

    const [filterState, setFilterState] = useState<FilterState>(getInitialState)

    // Save to sessionStorage whenever state changes
    useEffect(() => {
        if (typeof window === "undefined") return

        try {
            sessionStorage.setItem(fullKey, JSON.stringify(filterState))
        } catch (e) {
            console.warn("Failed to save filter state to storage:", e)
        }
    }, [filterState, fullKey])

    // Update URL if syncWithUrl is enabled
    useEffect(() => {
        if (!syncWithUrl) return

        const params = new URLSearchParams()
        if (filterState.statusFilter && filterState.statusFilter !== "all") {
            params.set("status", filterState.statusFilter)
        }
        if (filterState.searchQuery) {
            params.set("search", filterState.searchQuery)
        }
        if (filterState.page && filterState.page > 1) {
            params.set("page", filterState.page.toString())
        }

        const queryString = params.toString()
        const newUrl = queryString ? `${pathname}?${queryString}` : pathname

        // Only update if URL would change
        const currentQuery = searchParams?.toString() || ""
        if (queryString !== currentQuery) {
            router.replace(newUrl, { scroll: false })
        }
    }, [filterState, syncWithUrl, pathname, router, searchParams])

    // Convenience setters
    const setSearchQuery = useCallback((query: string) => {
        setFilterState(prev => ({ ...prev, searchQuery: query, page: 1 }))
    }, [])

    const setStatusFilter = useCallback((status: string) => {
        setFilterState(prev => ({ ...prev, statusFilter: status, page: 1 }))
    }, [])

    const setDateRange = useCallback((range: DateRange | undefined) => {
        setFilterState(prev => ({ ...prev, dateRange: range, page: 1 }))
    }, [])

    const setPage = useCallback((page: number) => {
        setFilterState(prev => ({ ...prev, page }))
    }, [])

    const setItemsPerPage = useCallback((count: number) => {
        setFilterState(prev => ({ ...prev, itemsPerPage: count, page: 1 }))
    }, [])

    const setSort = useCallback((column: string, direction: "asc" | "desc") => {
        setFilterState(prev => ({ ...prev, sortColumn: column, sortDirection: direction }))
    }, [])

    const clearFilters = useCallback(() => {
        setFilterState(defaults)
    }, [defaults])

    const hasActiveFilters = Boolean(
        filterState.searchQuery ||
        (filterState.statusFilter && filterState.statusFilter !== "all") ||
        filterState.dateRange?.from
    )

    return {
        ...filterState,
        setFilterState,
        setSearchQuery,
        setStatusFilter,
        setDateRange,
        setPage,
        setItemsPerPage,
        setSort,
        clearFilters,
        hasActiveFilters
    }
}
