import React from 'react'

import { DEPS, type IssueRef } from '../../data/fixtures.js'
import { Tag, Icon } from '../ui/index.js'

// Dependency graph drill-in — layered DAG, critical path in spruce
export function DepsGraph({ onOpenIssue }: { onOpenIssue: (issue: IssueRef) => void }) {
  const g = DEPS

  const PAD = 14, COLW = 206, ROWH = 106, NW = 176, NH = 84
  const X = (c: number) => PAD + c * COLW
  const Y = (r: number) => PAD + r * ROWH
  const maxCol = g.milestone.col
  const maxRow = Math.max(...g.nodes.map((n) => n.row), g.milestone.row)
  const W = PAD * 2 + maxCol * COLW + NW
  const H = PAD * 2 + maxRow * ROWH + NH
  const MSW = 158, MSH = 44

  const pos: Record<string, { x: number; y: number; w: number; h: number }> = {}
  g.nodes.forEach((n) => { pos[n.id] = { x: X(n.col), y: Y(n.row), w: NW, h: NH } })
  pos['ms'] = { x: X(g.milestone.col), y: Y(g.milestone.row) + (NH - MSH) / 2, w: MSW, h: MSH }

  const edgePath = (e: { from: number; to: number | 'ms'; crit?: boolean }) => {
    const a = pos[e.from], b = pos[e.to]
    const x1 = a.x + a.w, y1 = a.y + a.h / 2
    const x2 = b.x, y2 = b.y + b.h / 2
    const dx = Math.max(28, (x2 - x1) / 2)
    return `M ${x1} ${y1} C ${x1 + dx} ${y1}, ${x2 - dx} ${y2}, ${x2 - 5} ${y2}`
  }

  const STATES: Record<string, { icon: string; color: string; label: string }> = {
    done: { icon: 'circle-check', color: 'var(--ok)', label: 'done' },
    steeping: { icon: 'clock', color: 'var(--warn)', label: 'steeping' },
    review: { icon: 'git-pull-request', color: 'var(--info)', label: 'in review' },
    triage: { icon: 'circle-dot', color: 'var(--ink-3)', label: 'triage' },
    diagnosis: { icon: 'circle-dashed', color: 'var(--ink-3)', label: 'diagnosis' },
  }

  const Node = ({ n }: { n: (typeof DEPS.nodes)[number] }) => {
    const st = STATES[n.state]
    const crit = g.critical.includes(n.id)
    return (
      <div
        onClick={() => onOpenIssue({ id: n.id, title: n.title, labels: n.tags, rationale: n.rationale, days: n.state === 'steeping' ? n.days : undefined })}
        style={{
          position: 'absolute', left: pos[n.id].x, top: pos[n.id].y, width: NW, height: NH,
          background: n.state === 'done' ? 'var(--paper-2)' : 'var(--surface-card)',
          border: `1px solid ${crit ? 'var(--spruce-5)' : 'var(--line-1)'}`,
          boxShadow: crit ? 'var(--shadow-1), inset 2px 0 0 var(--accent)' : 'var(--shadow-1)',
          borderRadius: 'var(--radius-2)', padding: '9px 11px', cursor: 'pointer',
          display: 'flex', flexDirection: 'column', gap: 6,
          opacity: n.state === 'done' ? 0.72 : 1,
          transition: 'border-color var(--duration-fast) var(--ease-out)',
        }}
        onMouseEnter={(e: React.MouseEvent<HTMLDivElement>) => { e.currentTarget.style.borderColor = crit ? 'var(--accent)' : 'var(--line-2)' }}
        onMouseLeave={(e: React.MouseEvent<HTMLDivElement>) => { e.currentTarget.style.borderColor = crit ? 'var(--spruce-5)' : 'var(--line-1)' }}
      >
        <div style={{
          font: '500 12px/1.3 var(--font-sans)', color: 'var(--ink-1)',
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
        }}>{n.title}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 'auto' }}>
          <span style={{ font: '400 11px var(--font-mono)', color: 'var(--ink-3)' }}>#{n.id}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, font: '400 10.5px var(--font-mono)', color: st.color, whiteSpace: 'nowrap' }}>
            <Icon name={st.icon} size={11} />
            {st.label}{n.state === 'steeping' && n.days ? ` ${n.days}` : ''}
          </span>
          {n.tags.filter((t) => t.startsWith('p/')).map((t) => (
            <span key={t} style={{ font: '500 10.5px var(--font-mono)', color: 'var(--ink-3)', marginLeft: 'auto' }}>{t}</span>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12, flex: 1, minHeight: 0 }}>
      {/* legend */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 18, font: '400 11.5px var(--font-mono)', color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
          <span style={{ width: 22, height: 2, background: 'var(--accent)', display: 'inline-block' }}></span>critical path
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
          <span style={{ width: 22, height: 0, borderTop: '1.5px solid var(--line-2)', display: 'inline-block' }}></span>blocks
        </span>
        <span style={{ marginLeft: 'auto', color: 'var(--ink-3)' }}>unattached: {g.unattached.map((i) => `#${i}`).join(' · ')}</span>
      </div>

      {/* graph canvas */}
      <div style={{ overflow: 'auto', flex: 1, minHeight: 0, border: '1px solid var(--line-1)', borderRadius: 'var(--radius-3)', background: 'var(--surface-app)' }}>
        <div style={{ position: 'relative', width: W, height: H }}>
          <svg width={W} height={H} style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
            <defs>
              <marker id="dg-arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
                <path d="M 0 0.5 L 7.5 4 L 0 7.5 z" fill="var(--line-2)"></path>
              </marker>
              <marker id="dg-arrow-crit" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
                <path d="M 0 0.5 L 7.5 4 L 0 7.5 z" fill="var(--accent)"></path>
              </marker>
            </defs>
            {g.edges.map((e, i) => (
              <path key={i} d={edgePath(e)} fill="none"
                    stroke={e.crit ? 'var(--accent)' : 'var(--line-2)'}
                    strokeWidth={e.crit ? 2 : 1.5}
                    markerEnd={`url(#${e.crit ? 'dg-arrow-crit' : 'dg-arrow'})`} />
            ))}
          </svg>
          {g.nodes.map((n) => <Node key={n.id} n={n} />)}
          {/* milestone terminal */}
          <div style={{
            position: 'absolute', left: pos['ms'].x, top: pos['ms'].y, width: MSW, height: MSH,
            display: 'flex', alignItems: 'center', gap: 8, padding: '0 14px',
            background: 'var(--accent)', color: 'var(--ink-inverse)',
            borderRadius: 'var(--radius-round)', boxShadow: 'var(--shadow-2)',
          }}>
            <Icon name="milestone" size={15} />
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <span style={{ font: '600 12.5px/1.2 var(--font-sans)' }}>{g.milestone.name}</span>
              <span style={{ font: '400 10.5px/1.2 var(--font-mono)', opacity: 0.8 }}>due {g.milestone.due}</span>
            </div>
          </div>
        </div>
      </div>

      <p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: 0 }}>
        Four issues sit on the critical path, and #87 is the cork in the bottle. Remove it and everything pours.
      </p>
    </div>
  )
}
