import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { VisibilityState } from '@tanstack/vue-table'

// Default column visibility - basic columns visible, task type columns hidden by default
const DEFAULT_VISIBILITY: VisibilityState = {
  thumbnail: true,
  name: true,
  episode: true,
  frames: true,
  status: true,
}

const STORAGE_KEY = 'shot-column-visibility'

export const useColumnVisibilityStore = defineStore('columnVisibility', () => {
  // State
  const columnVisibility = ref<VisibilityState>({})
  let isInitialized = false

  // Getters
  const visibility = computed(() => {
    // Auto-initialize if empty
    if (Object.keys(columnVisibility.value).length === 0) {
      initialize()
    }
    return columnVisibility.value
  })

  const isColumnVisible = (columnId: string): boolean => {
    // Auto-initialize if empty
    if (Object.keys(columnVisibility.value).length === 0) {
      initialize()
    }
    // If not in visibility state, column is visible by default
    return columnVisibility.value[columnId] !== false
  }

  const visibleColumns = computed(() => {
    return Object.entries(columnVisibility.value)
      .filter(([, visible]) => visible !== false)
      .map(([column]) => column)
  })

  // Actions
  const initialize = () => {
    if (isInitialized) return
    
    // Get saved visibility from localStorage
    const saved = localStorage.getItem(STORAGE_KEY)
    if (saved) {
      try {
        const parsed = JSON.parse(saved)
        // Merge with defaults to ensure all columns have a state
        columnVisibility.value = { ...DEFAULT_VISIBILITY, ...parsed }
      } catch {
        // If parsing fails, use defaults
        columnVisibility.value = { ...DEFAULT_VISIBILITY }
      }
    } else {
      // No saved state, use defaults
      columnVisibility.value = { ...DEFAULT_VISIBILITY }
    }
    
    isInitialized = true
  }

  const toggleColumn = (columnId: string) => {
    const newVisibility = !isColumnVisible(columnId)
    updateColumn(columnId, newVisibility)
  }

  const updateColumn = (columnId: string, visible: boolean) => {
    columnVisibility.value = {
      ...columnVisibility.value,
      [columnId]: visible,
    }
    saveToStorage()
  }

  const setColumnVisibility = (visibility: VisibilityState) => {
    columnVisibility.value = { ...DEFAULT_VISIBILITY, ...visibility }
    saveToStorage()
  }

  const resetToDefaults = () => {
    columnVisibility.value = { ...DEFAULT_VISIBILITY }
    saveToStorage()
  }

  const saveToStorage = () => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(columnVisibility.value))
  }

  return {
    // State
    columnVisibility,
    
    // Getters
    visibility,
    isColumnVisible,
    visibleColumns,
    
    // Actions
    initialize,
    toggleColumn,
    updateColumn,
    setColumnVisibility,
    resetToDefaults,
  }
})
