import { createSlice, type PayloadAction } from '@reduxjs/toolkit'

/**
 * 主题模式
 */
export type ThemeMode = 'light' | 'dark' | 'auto'

/**
 * 布局模式
 */
export type LayoutMode = 'desktop' | 'tablet' | 'mobile'

/**
 * 控制面板配置
 */
export interface ControlPanelConfig {
  showKeyboard: boolean
  showGamepad: boolean
  showQuickActions: boolean
  showDeviceInfo: boolean
  position: 'left' | 'right' | 'bottom'
  collapsed: boolean
}

/**
 * 屏幕显示配置
 */
export interface ScreenDisplayConfig {
  fitMode: 'fit' | 'fill' | 'stretch' | 'original'
  quality: 'low' | 'medium' | 'high' | 'ultra'
  showTouchIndicator: boolean
  enableSound: boolean
  fullscreen: boolean
  exposure: number
}

/**
 * 屏幕阅读器配置
 */
export interface ScreenReaderConfig {
  enabled: boolean
  autoRefresh: boolean
  refreshInterval: number // 秒
  showElementBounds: boolean
  showElementHierarchy: boolean
  highlightClickable: boolean
}

/**
 * 相册图片信息
 */
export interface GalleryImage {
  id: string
  deviceId: string
  index: number
  displayName: string
  dateAdded: number
  mimeType: string
  width: number
  height: number
  size: number
  contentUri: string
  timestamp: number
  url: string
}

/**
 * 相册状态
 */
export interface GalleryState {
  images: GalleryImage[]
  loading: boolean
  visible: boolean
  selectedImageId: string | null
}

/**
 * UI状态管理
 */
interface UiState {
  theme: ThemeMode
  layout: LayoutMode
  controlPanel: ControlPanelConfig
  screenDisplay: ScreenDisplayConfig
  screenReader: ScreenReaderConfig
  sidebarCollapsed: boolean
  showSettings: boolean
  showAbout: boolean
  showDeviceList: boolean
  loading: boolean
  operationEnabled: boolean // 操作控制状态
  deviceInputBlocked: boolean // 设备端输入阻止状态
  cameraViewVisible: boolean // 摄像头显示区域可见性
  cameraActive: boolean // 摄像头是否有数据流（在线）
  gallery: GalleryState // 相册状态
  notifications: Array<{
    id: string
    type: 'success' | 'warning' | 'error' | 'info'
    title: string
    message: string
    duration?: number
    timestamp: number
  }>
}

const initialState: UiState = {
  theme: 'auto',
  layout: 'desktop',
  controlPanel: {
    showKeyboard: true,
    showGamepad: false,
    showQuickActions: true,
    showDeviceInfo: true,
    position: 'right',
    collapsed: false,
  },
  screenDisplay: {
    fitMode: 'fit',
    quality: 'high',
    showTouchIndicator: true,
    enableSound: false,
    fullscreen: false,
    exposure: 100,
  },
  screenReader: {
    enabled: false,
    autoRefresh: true,
    refreshInterval: 1,
    showElementBounds: true,
    showElementHierarchy: true,
    highlightClickable: true,
  },
  sidebarCollapsed: false,
  showSettings: false,
  showAbout: false,
  showDeviceList: false,
  loading: false,
  operationEnabled: true, // 默认允许操作
  deviceInputBlocked: false, // 默认不阻止设备输入
  cameraViewVisible: false, // 默认不显示摄像头区域
  cameraActive: false, // 默认摄像头未激活
  gallery: {
    images: [],
    loading: false,
    visible: false,
    selectedImageId: null,
  },
  notifications: [],
}

/**
 * UI管理 Slice
 */
const uiSlice = createSlice({
  name: 'ui',
  initialState,
  reducers: {
    // 设置主题
    setTheme: (state, action: PayloadAction<ThemeMode>) => {
      state.theme = action.payload
    },
    
    // 设置布局模式
    setLayout: (state, action: PayloadAction<LayoutMode>) => {
      state.layout = action.payload
    },
    
    // 更新控制面板配置
    updateControlPanel: (state, action: PayloadAction<Partial<ControlPanelConfig>>) => {
      state.controlPanel = { ...state.controlPanel, ...action.payload }
    },
    
    // 更新屏幕显示配置
    updateScreenDisplay: (state, action: PayloadAction<Partial<ScreenDisplayConfig>>) => {
      state.screenDisplay = { ...state.screenDisplay, ...action.payload }
    },
    
    // 更新屏幕阅读器配置
    updateScreenReader: (state, action: PayloadAction<Partial<ScreenReaderConfig>>) => {
      state.screenReader = { ...state.screenReader, ...action.payload }
    },
    
    // 启用屏幕阅读器模式
    enableScreenReader: (state) => {
      state.screenReader.enabled = true
    },
    
    // 禁用屏幕阅读器模式
    disableScreenReader: (state) => {
      state.screenReader.enabled = false
    },
    
    // 切换屏幕阅读器模式
    toggleScreenReader: (state) => {
      state.screenReader.enabled = !state.screenReader.enabled
    },
    
    // 切换侧边栏
    toggleSidebar: (state) => {
      state.sidebarCollapsed = !state.sidebarCollapsed
    },
    
    // 设置侧边栏状态
    setSidebarCollapsed: (state, action: PayloadAction<boolean>) => {
      state.sidebarCollapsed = action.payload
    },
    
    // 显示设置对话框
    showSettings: (state) => {
      state.showSettings = true
    },
    
    // 隐藏设置对话框
    hideSettings: (state) => {
      state.showSettings = false
    },
    
    // 显示关于对话框
    showAbout: (state) => {
      state.showAbout = true
    },
    
    // 隐藏关于对话框
    hideAbout: (state) => {
      state.showAbout = false
    },
    
    // 显示设备列表
    showDeviceList: (state) => {
      state.showDeviceList = true
    },
    
    // 隐藏设备列表
    hideDeviceList: (state) => {
      state.showDeviceList = false
    },
    
    // 设置加载状态
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload
    },
    
    // 添加通知
    addNotification: (state, action: PayloadAction<Omit<UiState['notifications'][0], 'id' | 'timestamp'>>) => {
      const notification = {
        ...action.payload,
        id: Date.now().toString(),
        timestamp: Date.now(),
      }
      state.notifications.push(notification)
    },
    
    // 移除通知
    removeNotification: (state, action: PayloadAction<string>) => {
      state.notifications = state.notifications.filter(
        notification => notification.id !== action.payload
      )
    },
    
    // 清除所有通知
    clearNotifications: (state) => {
      state.notifications = []
    },
    
    // 切换全屏模式
    toggleFullscreen: (state) => {
      state.screenDisplay.fullscreen = !state.screenDisplay.fullscreen
    },
    
    // 切换控制面板
    toggleControlPanel: (state) => {
      state.controlPanel.collapsed = !state.controlPanel.collapsed
    },
    
    // 设置操作控制状态
    setOperationEnabled: (state, action: PayloadAction<boolean>) => {
      state.operationEnabled = action.payload
    },
    
    // 切换操作控制状态
    toggleOperationEnabled: (state) => {
      state.operationEnabled = !state.operationEnabled
    },
    
    // 设置设备输入阻止状态
    setDeviceInputBlocked: (state, action: PayloadAction<boolean>) => {
      state.deviceInputBlocked = action.payload
    },
    
    // 切换设备输入阻止状态
    toggleDeviceInputBlocked: (state) => {
      state.deviceInputBlocked = !state.deviceInputBlocked
    },
    
    // 设置摄像头显示区域可见性
    setCameraViewVisible: (state, action: PayloadAction<boolean>) => {
      state.cameraViewVisible = action.payload
    },
    
    // 切换摄像头显示区域可见性
    toggleCameraViewVisible: (state) => {
      state.cameraViewVisible = !state.cameraViewVisible
    },

    // 设置摄像头激活状态（基于数据流）
    setCameraActive: (state, action: PayloadAction<boolean>) => {
      state.cameraActive = action.payload
    },

    // 设置相册可见性
    setGalleryVisible: (state, action: PayloadAction<boolean>) => {
      state.gallery.visible = action.payload
    },

    // 设置相册加载状态
    setGalleryLoading: (state, action: PayloadAction<boolean>) => {
      state.gallery.loading = action.payload
    },

    // 添加相册图片
    addGalleryImage: (state, action: PayloadAction<GalleryImage>) => {
      const existingIndex = state.gallery.images.findIndex(img => img.id === action.payload.id)
      if (existingIndex >= 0) {
        state.gallery.images[existingIndex] = action.payload
      } else {
        state.gallery.images.push(action.payload)
      }
      // 按时间戳倒序排列
      state.gallery.images.sort((a, b) => b.timestamp - a.timestamp)
    },

    // 设置相册图片列表
    setGalleryImages: (state, action: PayloadAction<GalleryImage[]>) => {
      state.gallery.images = action.payload.sort((a, b) => b.timestamp - a.timestamp)
    },

    // 选择相册图片
    selectGalleryImage: (state, action: PayloadAction<string | null>) => {
      state.gallery.selectedImageId = action.payload
    },

    // 清空相册
    clearGallery: (state) => {
      state.gallery.images = []
      state.gallery.selectedImageId = null
    },
  },
  extraReducers: (builder) => {
    // 监听设备状态重置，重置设备输入阻止状态
    builder.addCase('devices/resetDeviceStates', (state) => {
      state.deviceInputBlocked = false
    })
  },
})

export const {
  setTheme,
  setLayout,
  updateControlPanel,
  updateScreenDisplay,
  updateScreenReader,
  enableScreenReader,
  disableScreenReader,
  toggleScreenReader,
  toggleSidebar,
  setSidebarCollapsed,
  showSettings,
  hideSettings,
  showAbout,
  hideAbout,
  showDeviceList,
  hideDeviceList,
  setLoading,
  addNotification,
  removeNotification,
  clearNotifications,
  toggleFullscreen,
  toggleControlPanel,
  setOperationEnabled,
  toggleOperationEnabled,
  setDeviceInputBlocked,
  toggleDeviceInputBlocked,
  setCameraViewVisible,
  toggleCameraViewVisible,
  setCameraActive,
  setGalleryVisible,
  setGalleryLoading,
  addGalleryImage,
  setGalleryImages,
  selectGalleryImage,
  clearGallery,
} = uiSlice.actions

export default uiSlice.reducer 
