"use client"

import { useState, useMemo } from "react"

type SortOrder = "asc" | "desc"

interface UseSortableDataOptions<T> {
    initialSortBy?: keyof T | ""
    initialOrder?: SortOrder
}

export function useSortableData<T extends Record<string, any>>(data: T[], options?: UseSortableDataOptions<T>) {
    const [order, setOrder] = useState<SortOrder>(options?.initialOrder || "asc")
    const [sortBy, setSortBy] = useState<keyof T | "">(options?.initialSortBy || "")

    const handleSort = (property: keyof T) => {
        const isAsc = sortBy === property && order === "asc"
        setOrder(isAsc ? "desc" : "asc")
        setSortBy(property)
    }

    const sortedData = useMemo(() => {
        if (!sortBy) return [...data]

        return [...data].sort((a, b) => {
            const aValue = a[sortBy]
            const bValue = b[sortBy]

            if (typeof aValue === "string" && typeof bValue === "string") {
                return aValue.localeCompare(bValue) * (order === "asc" ? 1 : -1)
            }
            return (aValue < bValue ? -1 : 1) * (order === "asc" ? 1 : -1)
        })
    }, [data, order, sortBy])

    return {
        sortedData,
        order,
        sortBy,
        handleSort,
        setOrder,
        setSortBy,
    }
}
