import { useState, useEffect } from 'react'
import { getModelByName } from '../../../database/ObjectModels'

const useColumnVisibility = (type) => {
  const getInitialVisibility = () => {
    const stored = sessionStorage.getItem(`${type}_columnVisibility`)
    if (stored) {
      return JSON.parse(stored)
    }
    // Default visibility - all columns visible
    const model = getModelByName(type)
    const columns = model.columns || []
    return columns.reduce((acc, columnName) => {
      const property = model.properties?.find(
        (prop) => prop.name === columnName
      )
      if (property) {
        acc[property.name] = true
      }
      return acc
    }, {})
  }

  const [columnVisibility, setColumnVisibility] = useState(getInitialVisibility)

  useEffect(() => {
    sessionStorage.setItem(
      `${type}_columnVisibility`,
      JSON.stringify(columnVisibility)
    )
  }, [columnVisibility, type])

  const updateColumnVisibility = (key, value) => {
    setColumnVisibility((prev) => ({
      ...prev,
      [key]: value
    }))
  }

  return [columnVisibility, updateColumnVisibility]
}

export default useColumnVisibility
