<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useProjectsStore } from '@/stores/projects'
import type { GraphData } from '@/types'
import Button from '@/components/common/Button.vue'

const props = defineProps<{
  projectId: string
}>()

defineEmits<{
  close: []
}>()

const router = useRouter()
const projectsStore = useProjectsStore()

const graphData = ref<GraphData | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const depth = ref<1 | 2 | 3>(2)

// Node positions (computed by force simulation)
interface NodePos {
  id: string
  title: string
  x: number
  y: number
  vx: number
  vy: number
}

const nodePositions = ref<Map<string, NodePos>>(new Map())
const svgWidth = ref(800)
const svgHeight = ref(600)
const svgRef = ref<SVGSVGElement | null>(null)
const containerRef = ref<HTMLDivElement | null>(null)

async function loadGraph() {
  loading.value = true
  error.value = null
  try {
    graphData.value = await projectsStore.fetchProjectGraph(props.projectId, depth.value)
    initializePositions()
    runSimulation()
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Failed to load graph'
  } finally {
    loading.value = false
  }
}

function initializePositions() {
  if (!graphData.value) return
  const centerX = svgWidth.value / 2
  const centerY = svgHeight.value / 2
  const radius = Math.min(svgWidth.value, svgHeight.value) * 0.35

  const newPositions = new Map<string, NodePos>()
  graphData.value.nodes.forEach((node, i) => {
    const angle = (2 * Math.PI * i) / graphData.value!.nodes.length
    newPositions.set(node.id, {
      id: node.id,
      title: node.title,
      x: centerX + radius * Math.cos(angle),
      y: centerY + radius * Math.sin(angle),
      vx: 0,
      vy: 0
    })
  })
  nodePositions.value = newPositions
}

function runSimulation(iterations = 150) {
  if (!graphData.value) return

  for (let i = 0; i < iterations; i++) {
    simulateStep()
  }
}

function simulateStep() {
  if (!graphData.value) return
  const nodes = Array.from(nodePositions.value.values())
  const edges = graphData.value.edges

  const repulsion = 3000
  const attraction = 0.05
  const centering = 0.01
  const damping = 0.85

  // Repulsion between all nodes
  for (let a = 0; a < nodes.length; a++) {
    for (let b = a + 1; b < nodes.length; b++) {
      const na = nodes[a]
      const nb = nodes[b]
      const dx = nb.x - na.x
      const dy = nb.y - na.y
      const dist = Math.sqrt(dx * dx + dy * dy) || 1
      const force = repulsion / (dist * dist)
      const fx = (dx / dist) * force
      const fy = (dy / dist) * force
      na.vx -= fx
      na.vy -= fy
      nb.vx += fx
      nb.vy += fy
    }
  }

  // Attraction along edges
  for (const edge of edges) {
    const source = nodePositions.value.get(edge.source)
    const target = nodePositions.value.get(edge.target)
    if (!source || !target) continue
    const dx = target.x - source.x
    const dy = target.y - source.y
    const dist = Math.sqrt(dx * dx + dy * dy) || 1
    const force = (dist - 80) * attraction
    const fx = (dx / dist) * force
    const fy = (dy / dist) * force
    source.vx += fx
    source.vy += fy
    target.vx -= fx
    target.vy -= fy
  }

  // Centering force
  const centerX = svgWidth.value / 2
  const centerY = svgHeight.value / 2
  for (const node of nodes) {
    node.vx += (centerX - node.x) * centering
    node.vy += (centerY - node.y) * centering
  }

  // Apply velocities with damping
  for (const node of nodes) {
    node.vx *= damping
    node.vy *= damping
    node.x += node.vx
    node.y += node.vy

    // Keep within bounds
    node.x = Math.max(40, Math.min(svgWidth.value - 40, node.x))
    node.y = Math.max(40, Math.min(svgHeight.value - 40, node.y))

    nodePositions.value.set(node.id, node)
  }
}

function getEdgePath(sourceId: string, targetId: string): string {
  const source = nodePositions.value.get(sourceId)
  const target = nodePositions.value.get(targetId)
  if (!source || !target) return ''
  return `M ${source.x} ${source.y} L ${target.x} ${target.y}`
}

function handleNodeClick(nodeId: string) {
  router.push(`/documents/${nodeId}`)
}

function handleResize() {
  if (!containerRef.value) return
  svgWidth.value = containerRef.value.clientWidth
  svgHeight.value = containerRef.value.clientHeight
  if (graphData.value) {
    initializePositions()
    runSimulation(100)
  }
}

let resizeObserver: ResizeObserver | null = null

onMounted(async () => {
  if (containerRef.value) {
    svgWidth.value = containerRef.value.clientWidth
    svgHeight.value = containerRef.value.clientHeight
    resizeObserver = new ResizeObserver(handleResize)
    resizeObserver.observe(containerRef.value)
  }
  await loadGraph()
})

onUnmounted(() => {
  resizeObserver?.disconnect()
})

watch(depth, () => {
  loadGraph()
})
</script>

<template>
  <div class="graph-view">
    <div class="graph-view__header">
      <h2 class="graph-view__title">Project Graph</h2>
      <div class="graph-view__controls">
        <div class="graph-view__depth">
          <span class="graph-view__depth-label">Depth:</span>
          <Button
            v-for="d in [1, 2, 3] as const"
            :key="d"
            :variant="depth === d ? 'primary' : 'ghost'"
            size="sm"
            @click="depth = d"
          >{{ d }}</Button>
        </div>
        <Button variant="ghost" size="sm" @click="loadGraph">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M23 4v6h-6"/><path d="M1 20v-6h6"/>
            <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>
          </svg>
          Refresh
        </Button>
      </div>
    </div>

    <div v-if="graphData" class="graph-view__stats">
      <span>{{ graphData.stats.total_documents }} documents</span>
      <span>{{ graphData.stats.total_references }} references</span>
      <span v-if="graphData.stats.orphaned_documents > 0" class="graph-view__stat--warning">
        {{ graphData.stats.orphaned_documents }} orphaned
      </span>
    </div>

    <div ref="containerRef" class="graph-view__canvas">
      <div v-if="loading" class="graph-view__loading">
        <div class="graph-view__spinner"></div>
        Loading graph...
      </div>

      <div v-else-if="error" class="graph-view__error">
        {{ error }}
      </div>

      <svg
        v-else-if="graphData && nodePositions.size > 0"
        ref="svgRef"
        :width="svgWidth"
        :height="svgHeight"
        class="graph-view__svg"
      >
        <!-- Edges -->
        <g class="graph-view__edges">
          <path
            v-for="edge in graphData.edges"
            :key="`${edge.source}-${edge.target}`"
            :d="getEdgePath(edge.source, edge.target)"
            class="graph-view__edge"
          />
        </g>

        <!-- Nodes -->
        <g class="graph-view__nodes">
          <g
            v-for="[id, pos] in nodePositions"
            :key="id"
            class="graph-view__node"
            :transform="`translate(${pos.x}, ${pos.y})`"
            @click="handleNodeClick(id)"
          >
            <circle
              r="24"
              class="graph-view__node-circle"
            />
            <text
              class="graph-view__node-icon"
              text-anchor="middle"
              dominant-baseline="central"
              dy="0.05em"
            >📄</text>
            <title>{{ pos.title }}</title>
          </g>
        </g>
      </svg>

      <div v-else-if="graphData && graphData.nodes.length === 0" class="graph-view__empty">
        No documents in this project yet.
      </div>
    </div>

    <div class="graph-view__legend">
      <span>Click a node to open the document</span>
    </div>
  </div>
</template>

<style scoped>
.graph-view {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--bg-primary);
}

.graph-view__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid var(--border);
  flex-shrink: 0;
}

.graph-view__title {
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.graph-view__controls {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.graph-view__depth {
  display: flex;
  align-items: center;
  gap: 0.375rem;
}

.graph-view__depth-label {
  font-size: 0.8125rem;
  color: var(--text-secondary);
  margin-right: 0.25rem;
}

.graph-view__stats {
  display: flex;
  gap: 1.5rem;
  padding: 0.625rem 1.5rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border);
  font-size: 0.8125rem;
  color: var(--text-secondary);
  flex-shrink: 0;
}

.graph-view__stat--warning {
  color: #f59e0b;
}

.graph-view__canvas {
  flex: 1;
  position: relative;
  overflow: hidden;
  min-height: 300px;
}

.graph-view__loading,
.graph-view__error,
.graph-view__empty {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  color: var(--text-secondary);
  font-size: 0.875rem;
}

.graph-view__spinner {
  width: 24px;
  height: 24px;
  border: 2px solid var(--border);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 0.6s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.graph-view__svg {
  display: block;
  cursor: default;
}

.graph-view__edge {
  stroke: var(--border);
  stroke-width: 1.5;
  fill: none;
  transition: stroke 0.15s;
}

.graph-view__node-circle {
  fill: var(--bg-secondary);
  stroke: var(--accent);
  stroke-width: 2;
  cursor: pointer;
  transition: fill 0.15s, stroke 0.15s, transform 0.15s;
}

.graph-view__node:hover .graph-view__node-circle {
  fill: var(--accent);
  stroke: var(--accent-hover);
  transform: scale(1.1);
}

.graph-view__node-icon {
  font-size: 14px;
  pointer-events: none;
  user-select: none;
}

.graph-view__legend {
  padding: 0.5rem 1.5rem;
  border-top: 1px solid var(--border);
  font-size: 0.75rem;
  color: var(--text-secondary);
  text-align: center;
  flex-shrink: 0;
}
</style>
