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

const useColumnVisibility = (type, customColumns) => {
  const getInitialVisibility = () => {
    const storageKey = `${type}_columnVisibility`
    const stored = sessionStorage.getItem(storageKey)
    if (stored) {
      return JSON.parse(stored)
    }
    // Default visibility - all columns visible
    if (customColumns && Array.isArray(customColumns)) {
      return customColumns.reduce((acc, col) => {
        if (col.key) {
          acc[col.key] = true
        }
        return acc
      }, {})
    }
    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
