import { useCallback, useContext, useMemo } from 'react'
import { getModelByName } from '../../../database/ObjectModels'
import { ApiServerContext } from '../context/ApiServerContext'

const useColumnVisibility = (type, customColumns) => {
  const { userSettings, updateUserSettings } = useContext(ApiServerContext)
  const defaultVisibility = useMemo(() => {
    // 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
    }, {})
  }, [customColumns, type])

  const columnVisibility =
    userSettings.columnVisibility[type] ?? defaultVisibility

  const updateColumnVisibility = useCallback(
    (key, value) => {
      updateUserSettings('columnVisibility', type, {
        ...columnVisibility,
        [key]: value
      })
    },
    [columnVisibility, type, updateUserSettings]
  )

  return [columnVisibility, updateColumnVisibility]
}

export default useColumnVisibility
