import { ref } from 'vue'
import { extraAgentPool } from './useFlowLayout'
import type { AgentNodeData } from './useFlowLayout'

interface FlowBoardAgentStore {
  agents: AgentNodeData[]
  models: Array<{ id: string; alias: string }>
  changeModel: (agentId: string, modelId: string) => void
  selectAgent: (id: string | null) => void
}

interface FlowBoardChatStore {
  sendMessage: (text: string) => void
}

const STORAGE_KEY = 'nexus-flow-positions'

function readStoredPositions() {
  if (typeof window === 'undefined') return {}
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY)
    return raw ? JSON.parse(raw) as Record<string, { x: number; y: number }> : {}
  } catch {
    return {}
  }
}

export function useFlowBoardState(agentStore: FlowBoardAgentStore, chatStore: FlowBoardChatStore) {
  const agentPositions = ref<Record<string, { x: number; y: number }>>(readStoredPositions())
  const enteringIds = ref<string[]>([])
  const localAgentPool = ref<AgentNodeData[]>([...extraAgentPool])

  function selectAgent(id: string) {
    agentStore.selectAgent(id)
  }

  function closeAgent() {
    agentStore.selectAgent(null)
  }

  function changeModel(agentId: string, modelAlias: string) {
    const model = agentStore.models.find(m => m.alias === modelAlias)
    const modelId = model?.id ?? modelAlias
    agentStore.changeModel(agentId, modelId)
  }

  function addAgent() {
    const next = localAgentPool.value.shift()
    if (!next) return

    enteringIds.value = [...enteringIds.value, next.id]
    agentStore.agents.push(next)

    window.setTimeout(() => {
      enteringIds.value = enteringIds.value.filter(id => id !== next.id)
    }, 600)
  }

  function resetLayout() {
    agentPositions.value = {}
    if (typeof window !== 'undefined') window.localStorage.removeItem(STORAGE_KEY)
  }

  function updatePositions(positions: Record<string, { x: number; y: number }>) {
    agentPositions.value = { ...positions }
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify(agentPositions.value))
    }
  }

  function sendChatMessage(text: string) {
    chatStore.sendMessage(text)
  }

  return {
    addAgent,
    agentPositions,
    changeModel,
    closeAgent,
    enteringIds,
    resetLayout,
    selectAgent,
    sendChatMessage,
    updatePositions,
  }
}
