import { useMemo } from 'react';
import * as THREE from 'three';
import EdgeLines from './EdgeLines';
import { useLabels } from './useViewportLabels';

function dimValue(dimensions, key) {
  const d = dimensions?.find(d => d.dimension_key === key || d.dimension_name === key);
  return d?.value_mm;
}

export default function ComponentModel({ component, dimensions, selected = false, onSelect, opacity = 1, showPivot = true, onPaint }) {
  const { height, width, depth } = useMemo(() => ({
    height: dimValue(dimensions, 'overall_height') || dimValue(dimensions, 'system_height_mm') || 130,
    width: dimValue(dimensions, 'overall_max_width') || 82,
    depth: dimValue(dimensions, 'overall_max_depth') || 72,
  }), [dimensions]);

  const boxGeom = useMemo(() => new THREE.BoxGeometry(width, height, depth), [width, height, depth]);

  const handleClick = (e) => {
    if (onPaint) { e.stopPropagation(); onPaint(e.point); return; }
    e.stopPropagation(); onSelect?.('component', component);
  };

  useLabels([
    { id: 'cmp-pivot', position: [8, 0, 0], title: 'Pivot', tone: 'cyan' },
    { id: 'cmp-proximal', position: [0, height / 2 + 14, 0], title: 'Proximal', tone: 'slate' },
    { id: 'cmp-distal', position: [0, -height / 2 - 14, 0], title: 'Distal', tone: 'slate' },
    { id: 'cmp-button', position: [0, height / 2 - 5, depth / 2 + 8], title: 'Button', tone: 'amber' },
  ]);

  return (
    <group>
      <mesh geometry={boxGeom} onClick={handleClick} onPointerDown={onPaint ? (e) => { e.stopPropagation(); onPaint(e.point); } : undefined}>
        <meshStandardMaterial
          color={selected ? '#3a4a5a' : '#2a3038'}
          metalness={0.7}
          roughness={0.35}
          transparent={opacity < 1}
          opacity={opacity}
          emissive={selected ? '#22d3ee' : '#000000'}
          emissiveIntensity={selected ? 0.12 : 0}
        />
        <EdgeLines geometry={boxGeom} color={selected ? '#22d3ee' : '#4a5560'} opacity={opacity * 0.8} />
      </mesh>

      {showPivot && (
        <group>
          <mesh position={[0, 0, 0]}>
            <sphereGeometry args={[5, 16, 16]} />
            <meshStandardMaterial color="#22d3ee" emissive="#22d3ee" emissiveIntensity={0.6} />
          </mesh>
        </group>
      )}

      <mesh position={[0, height / 2 + 4, 0]}>
        <cylinderGeometry args={[width / 3.5, width / 3.5, 12, 24]} />
        <meshStandardMaterial color="#3a4550" metalness={0.85} roughness={0.25} />
      </mesh>

      <mesh position={[0, -height / 2 - 4, 0]}>
        <cylinderGeometry args={[width / 4.5, width / 4.5, 12, 24]} />
        <meshStandardMaterial color="#3a4550" metalness={0.85} roughness={0.25} />
      </mesh>

      <mesh position={[0, height / 2 - 5, depth / 2 + 1]}>
        <boxGeometry args={[10, 6, 3]} />
        <meshStandardMaterial color="#22d3ee" emissive="#22d3ee" emissiveIntensity={0.3} />
      </mesh>
    </group>
  );
}