import { MeshBuilder, StandardMaterial, Color3, Vector3, Mesh } from '@babylonjs/core';

/**
 * OssiguardConnectorLayer — optional, independently-isolated Babylon layer.
 * Renders conceptual connector placement, attachment points, keep-out zones,
 * and insertion/removal direction indicators.
 *
 * If exact Ossiguard CAD is unavailable, displays a conceptual placement mesh.
 * Never invents finished connector geometry — this is a visual placeholder.
 * Fails independently without crashing the prosthetic viewport.
 */
export function buildOssiguardConnector(scene, geometry, profile) {
  if (!profile) {
    return { meshes: [], labels: [], setVisible: () => {}, update: () => {}, dispose: () => {} };
  }

  const root = new Mesh('ossiguard-root', scene);
  root.isPickable = false;
  const meshes = [root];
  const mats = [];
  const labels = [];

  const w = Math.max((profile.overall_width_mm || 60) / 1000, 0.03);
  const d = Math.max((profile.overall_depth_mm || 40) / 1000, 0.03);
  const h = Math.max((profile.overall_height_mm || 50) / 1000, 0.03);

  const posX = 0.36;
  const posY = 3.0;
  const posZ = 0.30;

  // --- Connector body (purple — selected / conceptual) ---
  const bodyMat = new StandardMaterial('ossiguard-body-mat', scene);
  bodyMat.diffuseColor = Color3.FromHexString('#7E3FF2');
  bodyMat.emissiveColor = Color3.FromHexString('#7E3FF2').scale(0.45);
  bodyMat.alpha = 0.72;
  bodyMat.transparencyMode = 2;
  bodyMat.backFaceCulling = false;
  mats.push(bodyMat);

  const body = MeshBuilder.CreateBox('ossiguard-body', { width: w, depth: d, height: h }, scene);
  body.material = bodyMat;
  body.position = new Vector3(posX, posY, posZ);
  body.parent = root;
  body.metadata = { type: 'ossiguard', partId: 'ossiguard-connector', label: `${profile.profile_name || 'Ossiguard'} Connector` };
  meshes.push(body);

  // --- Attachment points (green — verified) ---
  const apCount = Math.min(profile.attachment_point_count || 2, 8);
  if (apCount > 0) {
    const apMat = new StandardMaterial('ossiguard-ap-mat', scene);
    apMat.emissiveColor = Color3.FromHexString('#22D37D');
    apMat.diffuseColor = Color3.FromHexString('#22D37D');
    apMat.specularColor = new Color3(0, 0, 0);
    mats.push(apMat);

    for (let i = 0; i < apCount; i++) {
      const angle = (i / apCount) * Math.PI * 2;
      const ap = MeshBuilder.CreateSphere(`ossiguard-ap-${i}`, { diameter: 0.035, segments: 8 }, scene);
      ap.material = apMat;
      ap.position = new Vector3(
        posX + Math.cos(angle) * (w / 2 + 0.015),
        posY + (i % 2 === 0 ? h / 4 : -h / 4),
        posZ + Math.sin(angle) * (d / 2 + 0.015)
      );
      ap.parent = root;
      ap.metadata = { type: 'ossiguard', partId: `ossiguard-ap-${i}`, label: `Attachment point ${i + 1}` };
      meshes.push(ap);
    }
  }

  // --- Keep-out / clearance zone (red — prohibited region) ---
  const koMat = new StandardMaterial('ossiguard-ko-mat', scene);
  koMat.diffuseColor = Color3.FromHexString('#FF4D62');
  koMat.emissiveColor = Color3.FromHexString('#FF4D62').scale(0.15);
  koMat.alpha = 0.16;
  koMat.transparencyMode = 2;
  koMat.wireframe = true;
  mats.push(koMat);

  const ko = MeshBuilder.CreateBox('ossiguard-keepout', { width: w + 0.06, depth: d + 0.06, height: h + 0.08 }, scene);
  ko.material = koMat;
  ko.position = new Vector3(posX, posY, posZ);
  ko.parent = root;
  ko.isPickable = false;
  ko.metadata = { type: 'ossiguard', partId: 'ossiguard-keepout', label: 'Keep-out / clearance zone' };
  meshes.push(ko);

  // --- Insertion direction arrow (green, pointing up) ---
  try {
    const insMat = new StandardMaterial('ossiguard-insert-mat', scene);
    insMat.emissiveColor = Color3.FromHexString('#62F2A8');
    insMat.diffuseColor = Color3.FromHexString('#22D37D');
    insMat.specularColor = new Color3(0, 0, 0);
    mats.push(insMat);

    const insArrow = MeshBuilder.CreateCylinder('ossiguard-insert-arrow', { diameterTop: 0, diameterBottom: 0.025, height: 0.1, tessellation: 8 }, scene);
    insArrow.material = insMat;
    insArrow.position = new Vector3(posX, posY + h / 2 + 0.07, posZ);
    insArrow.parent = root;
    insArrow.isPickable = false;
    insArrow.metadata = { type: 'ossiguard', partId: 'ossiguard-insert', label: `Insertion direction: ${profile.insertion_direction || 'not recorded'}` };
    meshes.push(insArrow);
  } catch (_) { /* arrow optional */ }

  // --- Removal direction arrow (amber, pointing lateral) ---
  try {
    const remMat = new StandardMaterial('ossiguard-remove-mat', scene);
    remMat.emissiveColor = Color3.FromHexString('#FFB347');
    remMat.diffuseColor = Color3.FromHexString('#FF8C00');
    remMat.specularColor = new Color3(0, 0, 0);
    mats.push(remMat);

    const remArrow = MeshBuilder.CreateCylinder('ossiguard-remove-arrow', { diameterTop: 0, diameterBottom: 0.022, height: 0.09, tessellation: 8 }, scene);
    remArrow.material = remMat;
    remArrow.rotation.z = Math.PI / 2;
    remArrow.position = new Vector3(posX + w / 2 + 0.07, posY, posZ);
    remArrow.parent = root;
    remArrow.isPickable = false;
    remArrow.metadata = { type: 'ossiguard', partId: 'ossiguard-remove', label: `Removal direction: ${profile.removal_direction || 'not recorded'}` };
    meshes.push(remArrow);
  } catch (_) { /* arrow optional */ }

  labels.push({
    id: 'ossiguard-label',
    position: [posX, posY + h / 2 + 0.16, posZ],
    text: profile.step_file_url || profile.stl_file_url
      ? `Ossiguard — ${profile.profile_name || 'connector'} rev${profile.connector_revision}`
      : 'Ossiguard conceptual placement — exact connector geometry not loaded',
    kind: 'warning',
    tone: 'purple',
  });

  return {
    mesh: body,
    meshes,
    labels,
    update(next = {}) {
      // Lightweight updates only — no geometry rebuild to keep viewport stable
    },
    setVisible(v) { meshes.forEach((m) => { try { m.setEnabled(v ? 1 : 0); } catch (_) {} }); },
    dispose() {
      meshes.forEach((m) => { try { m.dispose(); } catch (_) {} });
      mats.forEach((m) => { try { m.dispose(); } catch (_) {} });
    },
  };
}