"use client"

import { useCallback, useState } from "react"

import type { DashboardRole, DashboardWidgetConfig } from "@/modules/dashboard/types"
import { getWidgetConfig } from "@/modules/dashboard/config/widget-configs"

const STORAGE_KEY = "dashboard-widget-preferences"

/** 用户 Widget 偏好（widgetId → visible） */
export type WidgetPreferences = Record<string, boolean>

/**
 * 从 localStorage 读取偏好（同步，用于 lazy initializer）。
 */
function loadPreferences(role: DashboardRole): WidgetPreferences {
  if (typeof window === "undefined") return {}
  try {
    const stored = localStorage.getItem(`${STORAGE_KEY}-${role}`)
    return stored ? (JSON.parse(stored) as WidgetPreferences) : {}
  } catch {
    return {}
  }
}

/**
 * 仪表盘自定义偏好 Hook（L4）。
 *
 * 从 localStorage 读取用户对 Widget 显示/隐藏的偏好，
 * 与默认配置合并，支持运行时切换。
 *
 * - 首次访问返回默认配置的 `defaultVisible`
 * - 用户切换后持久化到 localStorage
 * - 支持重置为默认
 */
export function useDashboardPreferences(role: DashboardRole) {
  // 使用 lazy initializer 避免 useEffect 中调用 setState
  const [preferences, setPreferences] = useState<WidgetPreferences>(() => loadPreferences(role))

  const config = getWidgetConfig(role)

  /** 合并默认配置与用户偏好 */
  const effectiveWidgets: DashboardWidgetConfig[] = config.widgets.map((w) => ({
    ...w,
    defaultVisible: preferences[w.id] ?? w.defaultVisible,
  }))

  /** 切换某个 Widget 的可见性 */
  const toggleWidget = useCallback(
    (widgetId: string) => {
      setPreferences((prev) => {
        const widget = config.widgets.find((w) => w.id === widgetId)
        if (!widget) return prev
        const currentVisible = prev[widgetId] ?? widget.defaultVisible
        const next = { ...prev, [widgetId]: !currentVisible }
        try {
          localStorage.setItem(`${STORAGE_KEY}-${role}`, JSON.stringify(next))
        } catch {
          // localStorage 不可用，仅更新内存状态
        }
        return next
      })
    },
    [config.widgets, role],
  )

  /** 重置为默认配置 */
  const resetToDefault = useCallback(() => {
    setPreferences({})
    try {
      localStorage.removeItem(`${STORAGE_KEY}-${role}`)
    } catch {
      // localStorage 不可用
    }
  }, [role])

  return {
    widgets: effectiveWidgets,
    toggleWidget,
    resetToDefault,
  }
}
