import { useMemo } from 'react';
import type { WiringPath, WiringTerminal } from '../../api/types';
import './wiring.css';

/*
 * 배선 오버레이 렌더러 (SCR-07 히어로).
 * - 다크 서피스(#1C2536) 위 부스 폴리곤 + 트렌치 그리드 + 배선 경로.
 * - 색상 규약(design.md §1·S6·계약 §5): 전기 power=적 / 네트워크 network=청 / 급배수·압축공기 plumbing·air=녹.
 * - 좌표계: 홀 로컬 미터(계약 WiringResult.coords / terminal.position) → SVG 유저 유닛(1m=1unit).
 *   부스·트렌치·경로가 같은 좌표 공간을 공유(좌표 정합).
 */

interface WiringCanvasProps {
  /** 부스 폴리곤(홀 로컬 미터). 뷰포트 중심 대상. */
  boothPolygon: number[][];
  /** 배선 경로(계약 WiringResult.paths). */
  paths: WiringPath[];
  /** 단말(드래그 조정 대상). */
  terminals: WiringTerminal[];
  assumedTrench: boolean;
  selectedTerminalIdx: number | null;
  onSelectTerminal: (idx: number | null) => void;
}

const COLOR_CLASS: Record<string, string> = {
  power: 'is-power',
  red: 'is-power',
  network: 'is-network',
  blue: 'is-network',
  plumbing: 'is-water',
  air: 'is-water',
  green: 'is-water',
};

const TRENCH_SPACING_M = 3;
const PAD = 4; // viewBox 여백(m)

function bbox(poly: number[][]): { minX: number; minY: number; maxX: number; maxY: number } {
  let minX = Infinity;
  let minY = Infinity;
  let maxX = -Infinity;
  let maxY = -Infinity;
  for (const [x, y] of poly) {
    if (x < minX) minX = x;
    if (y < minY) minY = y;
    if (x > maxX) maxX = x;
    if (y > maxY) maxY = y;
  }
  return { minX, minY, maxX, maxY };
}

function kindClass(p: WiringPath): string {
  return COLOR_CLASS[p.color] ?? COLOR_CLASS[p.kind] ?? 'is-power';
}

export function WiringCanvas({
  boothPolygon,
  paths,
  terminals,
  assumedTrench,
  selectedTerminalIdx,
  onSelectTerminal,
}: WiringCanvasProps) {
  // 부스 주변 여유를 둔 뷰박스(부스 + 인접 트렌치가 보이게).
  const view = useMemo(() => {
    const b = bbox(boothPolygon);
    const marginX = Math.max(6, (b.maxX - b.minX) * 0.4);
    const marginY = Math.max(6, (b.maxY - b.minY) * 0.4);
    const minX = b.minX - marginX;
    const minY = b.minY - marginY;
    const w = b.maxX - b.minX + marginX * 2;
    const h = b.maxY - b.minY + marginY * 2;
    return { minX, minY, w, h };
  }, [boothPolygon]);

  // 뷰박스 범위의 트렌치 그리드(가정 그리드 — 실측 대기).
  const trench = useMemo(() => {
    const lines: { x1: number; y1: number; x2: number; y2: number }[] = [];
    const startX = Math.ceil((view.minX - PAD) / TRENCH_SPACING_M) * TRENCH_SPACING_M;
    const startY = Math.ceil((view.minY - PAD) / TRENCH_SPACING_M) * TRENCH_SPACING_M;
    for (let x = startX; x < view.minX + view.w + PAD; x += TRENCH_SPACING_M) {
      lines.push({ x1: x, y1: view.minY - PAD, x2: x, y2: view.minY + view.h + PAD });
    }
    for (let y = startY; y < view.minY + view.h + PAD; y += TRENCH_SPACING_M) {
      lines.push({ x1: view.minX - PAD, y1: y, x2: view.minX + view.w + PAD, y2: y });
    }
    return lines;
  }, [view]);

  const boothPts = boothPolygon.map(([x, y]) => `${x},${y}`).join(' ');

  return (
    <div className="kx-wire">
      {assumedTrench && (
        <span className="kx-wire__assumed" title="실측 트렌치 좌표 반영 전 — 가정 그리드">
          가정 트렌치 좌표 (실측 대기)
        </span>
      )}
      <div className="kx-wire__legend" aria-hidden="true">
        <span className="kx-wire__legend-item is-power">전기</span>
        <span className="kx-wire__legend-item is-network">네트워크</span>
        <span className="kx-wire__legend-item is-water">급배수</span>
      </div>

      <svg
        className="kx-wire__svg"
        viewBox={`${view.minX} ${view.minY} ${view.w} ${view.h}`}
        role="img"
        aria-label={`부스 배선 도면, 경로 ${paths.length}개`}
        onClick={() => onSelectTerminal(null)}
      >
        {/* 트렌치 그리드 */}
        <g className="kx-wire__trench">
          {trench.map((l, i) => (
            <line key={i} x1={l.x1} y1={l.y1} x2={l.x2} y2={l.y2} />
          ))}
        </g>

        {/* 부스 외곽 */}
        <polygon className="kx-wire__booth" points={boothPts} />

        {/* 배선 경로 (색상 규약) */}
        <g className="kx-wire__paths">
          {paths.map((p, i) => {
            const d = p.coords.map(([x, y], j) => `${j === 0 ? 'M' : 'L'} ${x} ${y}`).join(' ');
            const mid = p.coords[Math.floor(p.coords.length / 2)] ?? p.coords[0];
            return (
              <g key={i} className={`kx-wire__path ${kindClass(p)}`}>
                <path d={d} className="kx-wire__path-line" />
                {mid && (
                  <text x={mid[0]} y={mid[1] - 0.6} className="kx-wire__path-label">
                    {p.label}
                  </text>
                )}
              </g>
            );
          })}
        </g>

        {/* 단말 노드 */}
        <g className="kx-wire__terminals">
          {terminals.map((t, i) => {
            const [x, y] = t.position;
            const sel = i === selectedTerminalIdx;
            const cls = COLOR_CLASS[t.kind] ?? 'is-power';
            return (
              <g
                key={i}
                className={`kx-wire__terminal ${cls} ${sel ? 'is-selected' : ''}`}
                onClick={(e) => {
                  e.stopPropagation();
                  onSelectTerminal(i);
                }}
                tabIndex={0}
                role="button"
                aria-label={`단말 ${i + 1} (${t.kind})`}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    onSelectTerminal(i);
                  }
                }}
              >
                <circle cx={x} cy={y} r={0.9} />
              </g>
            );
          })}
        </g>
      </svg>
    </div>
  );
}
