import { create } from 'zustand'
import type { CameraStatus } from '../types'

interface CameraState {
  /** All cameras with latest status from SSE events */
  cameras: Map<string, CameraStatus>

  /** Replace the full camera list (e.g. on initial SSE or polling fallback) */
  setCameras: (cameras: CameraStatus[]) => void

  /** Upsert a single camera status from an SSE event */
  updateCamera: (camera: CameraStatus) => void

  /** Mark a camera offline */
  setOffline: (cameraId: string) => void

  /** Mark a camera online */
  setOnline: (cameraId: string) => void

  /** Update recording state from a recording_event */
  setRecording: (cameraId: string, recording: boolean) => void

  /** Derived: camera array (for UI consumption) */
  getCameras: () => CameraStatus[]

  /** Derived: online count */
  getOnlineCount: () => number

  /** Derived: recording count */
  getRecordingCount: () => number
}

export const useCameraStore = create<CameraState>((set, get) => ({
  cameras: new Map(),

  setCameras: (list) =>
    set((state) => {
      const next = new Map(state.cameras)
      for (const cam of list) {
        next.set(cam.camera_id, cam)
      }
      return { cameras: next }
    }),

  updateCamera: (camera) =>
    set((state) => {
      const next = new Map(state.cameras)
      next.set(camera.camera_id, camera)
      return { cameras: next }
    }),

  setOffline: (cameraId) =>
    set((state) => {
      const cam = state.cameras.get(cameraId)
      if (!cam) return state
      const next = new Map(state.cameras)
      next.set(cameraId, { ...cam, online: false })
      return { cameras: next }
    }),

  setOnline: (cameraId) =>
    set((state) => {
      const cam = state.cameras.get(cameraId)
      if (!cam) return state
      const next = new Map(state.cameras)
      next.set(cameraId, { ...cam, online: true })
      return { cameras: next }
    }),

  setRecording: (cameraId, recording) =>
    set((state) => {
      const cam = state.cameras.get(cameraId)
      if (!cam) return state
      const next = new Map(state.cameras)
      next.set(cameraId, { ...cam, recording })
      return { cameras: next }
    }),

  getCameras: () => Array.from(get().cameras.values()),

  getOnlineCount: () =>
    Array.from(get().cameras.values()).filter((c) => c.online).length,

  getRecordingCount: () =>
    Array.from(get().cameras.values()).filter((c) => c.recording).length,
}))
