/* eslint-disable @typescript-eslint/no-explicit-any */
"use client"

import { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
import './ModelViewer.css';
import TextToSpeech from './TextToSpeech';
import { Box, Button, CircularProgress } from '@mui/material';

type Label = {
  id: string;
  color?: string;
  title: string;
  normal: string;
  position: string;
  description?: string | null;
};

type LabelInfo = {
  element: HTMLDivElement;
  targetPosition: THREE.Vector3;
  marker: THREE.Mesh;
  line: THREE.Line;
};

type ThreeState = {
  scene: THREE.Scene | null;
  camera: THREE.PerspectiveCamera | null;
  renderer: THREE.WebGLRenderer | null;
  controls: OrbitControls | null;
  raycaster: THREE.Raycaster;
  mouse: THREE.Vector2;
  model: THREE.Group | null;
  modelMeshes: THREE.Mesh[];
  markers: THREE.Mesh[];
  labelInfos: LabelInfo[];
  animationId: number;
  labelOffset: THREE.Vector3;
  previewMarker: THREE.Mesh | null;
  pmremGenerator: THREE.PMREMGenerator | null;
};

type AddLabelData = {
  worldPosition: THREE.Vector3;
  position: string;
  normal: string;
};

interface ModelViewerProps {
  modelUrl?: string;
  speachtext?: string;
  labels?: Label[];
  background?: string;
  showHelpers?: boolean;
  enableAdd?: boolean;
  onAddLabel?: (data: AddLabelData) => void;
  previewPosition?: string;
  activeLabelId?: string | null;
  onClose?: () => void;
  alt?: string;
  shadowIntensity?: number;
  shadowSoftness?: number;
  exposure?: number;
  environmentImage?: string;
  cameraControls?: boolean;
  touchAction?: string;
  maxCameraOrbit?: string;
  minCameraOrbit?: string;
}

const parseVec3 = (value: string | number[] | { x: number; y: number; z: number } | undefined): THREE.Vector3 => {
  if (Array.isArray(value) && value.length >= 3) {
    return new THREE.Vector3(Number(value[0]), Number(value[1]), Number(value[2]));
  }
  if (typeof value === 'string') {
    const [x, y, z] = value.trim().split(/\s+/).map(Number);
    return new THREE.Vector3(x, y, z);
  }
  if (value && typeof value === 'object' && !Array.isArray(value)) {
    return new THREE.Vector3(Number(value.x), Number(value.y), Number(value.z));
  }
  return new THREE.Vector3();
};

const toVecString = (vec: THREE.Vector3): string => `${vec.x} ${vec.y} ${vec.z}`;

export default function ModelViewer({
  modelUrl = '/model.glb',
  speachtext = "",
  labels = [],
  background = '#0a0e1a',
  showHelpers = false,
  enableAdd = false,
  onAddLabel,
  onClose,
  previewPosition,
  activeLabelId,
  alt = "3D Model",
  shadowIntensity = 0.5,
  shadowSoftness = 0.5,
  exposure = 1,
  environmentImage = "neutral",
  cameraControls = true,
  touchAction = "pan-y",
  maxCameraOrbit = "auto 90deg auto",
}: ModelViewerProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const overlayRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState(true);
  const initialCamRef = useRef<{ pos: THREE.Vector3; target: THREE.Vector3 } | null>(null);
  const labelsRef = useRef<Label[]>(labels);
  const onAddLabelRef = useRef<((data: AddLabelData) => void) | undefined>(onAddLabel);
  const threeRef = useRef<ThreeState>({
    scene: null,
    camera: null,
    renderer: null,
    controls: null,
    raycaster: new THREE.Raycaster(),
    mouse: new THREE.Vector2(),
    model: null,
    modelMeshes: [],
    markers: [],
    labelInfos: [],
    animationId: 0,
    labelOffset: new THREE.Vector3(0.12, 0.18, 0.08),
    previewMarker: null,
    pmremGenerator: null,
  });

  useEffect(() => {
    labelsRef.current = labels;
  }, [labels]);

  useEffect(() => {
    onAddLabelRef.current = onAddLabel;
  }, [onAddLabel]);

  useEffect(() => {
    const container = containerRef.current;
    const overlay = overlayRef.current;
    if (!container || !overlay) return undefined;

    const state = threeRef.current;

    // Scene setup
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(background);
    state.scene = scene;

    const camera = new THREE.PerspectiveCamera(
      45,
      container.clientWidth / container.clientHeight,
      0.1,
      1000
    );
    camera.position.set(0, 2, 6);
    state.camera = camera;

    // Renderer with enhanced settings (model-viewer-like)
    const renderer = new THREE.WebGLRenderer({
      antialias: true,
      powerPreference: 'high-performance',
      alpha: true,
    });
    renderer.setSize(container.clientWidth, container.clientHeight);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    renderer.outputColorSpace = THREE.SRGBColorSpace;
    renderer.toneMapping = THREE.ACESFilmicToneMapping;
    renderer.toneMappingExposure = exposure;
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    container.appendChild(renderer.domElement);
    state.renderer = renderer;

    // PMREM Generator for environment maps
    const pmremGenerator = new THREE.PMREMGenerator(renderer);
    pmremGenerator.compileEquirectangularShader();
    state.pmremGenerator = pmremGenerator;

    // OrbitControls with model-viewer-like settings
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enabled = cameraControls;
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.minDistance = 1;
    controls.maxDistance = 50;
    
    // Parse maxCameraOrbit (e.g., "auto 90deg auto")
    const maxOrbitParts = maxCameraOrbit.split(' ');
    if (maxOrbitParts[1] && maxOrbitParts[1].includes('deg')) {
      const maxPolarAngle = parseFloat(maxOrbitParts[1]) * (Math.PI / 180);
      controls.maxPolarAngle = maxPolarAngle;
    }
    
    controls.target.set(0, 0, 0);
    controls.enablePan = touchAction.includes('pan');
    state.controls = controls;

    // Enhanced Lighting (model-viewer style)
    scene.add(new THREE.AmbientLight(0xffffff, 0.4));
    
    const keyLight = new THREE.DirectionalLight(0xffffff, 1.5);
    keyLight.position.set(5, 10, 7.5);
    keyLight.castShadow = true;
    keyLight.shadow.mapSize.width = 2048;
    keyLight.shadow.mapSize.height = 2048;
    keyLight.shadow.camera.near = 0.5;
    keyLight.shadow.camera.far = 50;
    keyLight.shadow.bias = -0.0001;
    keyLight.shadow.normalBias = 0.02;
    scene.add(keyLight);

    const fillLight = new THREE.DirectionalLight(0xffffff, 0.75);
    fillLight.position.set(-5, 5, -5);
    scene.add(fillLight);

    const backLight = new THREE.DirectionalLight(0xffffff, 0.5);
    backLight.position.set(0, 5, -10);
    scene.add(backLight);

    scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 0.6));

    // Ground plane for shadows
    if (shadowIntensity > 0) {
      const groundGeometry = new THREE.PlaneGeometry(100, 100);
      const groundMaterial = new THREE.ShadowMaterial({ 
        opacity: shadowIntensity,
        side: THREE.DoubleSide 
      });
      const ground = new THREE.Mesh(groundGeometry, groundMaterial);
      ground.rotation.x = -Math.PI / 2;
      ground.position.y = 0;
      ground.receiveShadow = true;
      scene.add(ground);
    }

    // Load environment map if specified
    if (environmentImage && environmentImage !== "neutral") {
      new RGBELoader().load(
        `/environments/${environmentImage}.hdr`,
        (texture) => {
          const envMap = pmremGenerator.fromEquirectangular(texture).texture;
          scene.environment = envMap;
          texture.dispose();
        },
        undefined,
        () => {
          // Fallback to neutral if load fails
          console.warn('Environment map load failed, using neutral');
        }
      );
    } else {
      // Create neutral environment
      const pmremGenerator = new THREE.PMREMGenerator(renderer);
      scene.environment = pmremGenerator.fromScene(new THREE.Scene()).texture;
    }

    if (showHelpers) {
      scene.add(new THREE.GridHelper(20, 20, 0x444466, 0x222244));
      scene.add(new THREE.AxesHelper(3));
    }

    const hideAllLabels = (exceptInfo: LabelInfo | null = null) => {
      state.labelInfos.forEach((info) => {
        if (exceptInfo && info === exceptInfo) return;
        info.element.style.display = 'none';
        info.line.visible = false;
      });
    };

    const addLabelPoint = (position: THREE.Vector3, name: string, color: string = '#3399ff', labelOffset: THREE.Vector3, id: string) => {
      const geo = new THREE.SphereGeometry(0.08, 16, 16);
      const mat = new THREE.MeshBasicMaterial({ color });
      const marker = new THREE.Mesh(geo, mat);
      marker.position.copy(position);
      marker.userData = { id, name, isMarker: true };
      scene.add(marker);
      state.markers.push(marker);

      const lineMat = new THREE.LineDashedMaterial({
        color: 0x88ccff,
        linewidth: 2,
        scale: 1,
        dashSize: 0.12,
        gapSize: 0.06,
      });
      const offset = position.clone().add(labelOffset);
      const lineGeo = new THREE.BufferGeometry().setFromPoints([position, offset]);
      const line = new THREE.Line(lineGeo, lineMat);
      line.computeLineDistances();
      line.visible = false;
      scene.add(line);

      const labelDiv = document.createElement('div');
      labelDiv.className = 'anatomy-label';
      const text = document.createElement('span');
      text.textContent = name;
      const close = document.createElement('button');
      close.className = 'close';
      close.type = 'button';
      close.setAttribute('aria-label', 'Close label');
      close.textContent = '×';
      labelDiv.append(text, close);
      labelDiv.style.display = 'none';

      close.onclick = (e) => {
        e.stopPropagation();
        labelDiv.style.display = 'none';
        line.visible = false;
      };

      overlay.appendChild(labelDiv);

      state.labelInfos.push({
        element: labelDiv,
        targetPosition: offset,
        marker,
        line,
      });
    };

    const clearLabels = () => {
      state.labelInfos.forEach(({ element, line }) => {
        if (element.parentNode) element.parentNode.removeChild(element);
        line.geometry.dispose();
        if (Array.isArray(line.material)) {
          line.material.forEach((mat: THREE.Material) => mat.dispose());
        } else if (line.material) {
          line.material.dispose();
        }
      });
      state.labelInfos = [];

      state.markers.forEach((m) => {
        m.geometry.dispose();
        if (Array.isArray(m.material)) {
          m.material.forEach((mat: THREE.Material) => mat.dispose());
        } else {
          (m.material as THREE.Material).dispose();
        }
        scene.remove(m);
      });
      state.markers = [];
    };

    const buildLabels = () => {
      if (!state.model) return;
      clearLabels();

      labelsRef.current.forEach((l) => {
        const localPos = parseVec3(l.position);
        const worldPos = state.model!.localToWorld(localPos.clone());
        addLabelPoint(worldPos, l.title, l.color, state.labelOffset, l.id);
      });
    };

    const loader = new GLTFLoader();

    loader.load(
      modelUrl,
      (gltf: { scene: any; }) => {
        const model = gltf.scene;
        state.model = model;
        
        // Enable shadows on model
        model.traverse((obj: any) => {
          if ((obj as THREE.Mesh).isMesh) {
            obj.castShadow = true;
            obj.receiveShadow = true;
            state.modelMeshes.push(obj as THREE.Mesh);
          }
        });

        scene.add(model);

        const box = new THREE.Box3().setFromObject(model);
        const center = box.getCenter(new THREE.Vector3());
        const size = box.getSize(new THREE.Vector3());
        const maxDim = Math.max(size.x, size.y, size.z);

        // Center model at origin
        model.position.sub(center);

        // Auto-scale to fit view
        const targetSize = 4;
        const scaleFactor = targetSize / maxDim;
        model.scale.setScalar(scaleFactor);

        // Position camera for optimal view
        const distance = maxDim * 2.5;
        camera.position.set(distance * 0.5, distance * 0.5, distance);
        controls.target.set(0, 0, 0);
        controls.update();

        state.labelOffset = new THREE.Vector3(0.12, 0.18, 0.08).multiplyScalar(targetSize);

        buildLabels();
        initialCamRef.current = {
          pos: camera.position.clone(),
          target: controls.target.clone(),
        };
        setLoading(false);
      },
      (progress) => {
        // Progress callback
        const percentComplete = (progress.loaded / progress.total) * 100;
        console.log(`Loading: ${percentComplete.toFixed(2)}%`);
      },
      (err: any) => {
        console.error('Model load error:', err);
        setLoading(false);
      }
    );

    const onClick = (event: MouseEvent) => {
      const rect = renderer.domElement.getBoundingClientRect();
      state.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
      state.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;

      state.raycaster.setFromCamera(state.mouse, camera);

      const markerHits = state.raycaster.intersectObjects(state.markers, false);
      if (markerHits.length > 0) {
        const clickedMarker = markerHits[0].object as THREE.Mesh;
        const info = state.labelInfos.find((l) => l.marker === clickedMarker);
        if (!info) return;

        const shouldShow = info.element.style.display === 'none';
        if (shouldShow) hideAllLabels(info);
        info.element.style.display = shouldShow ? 'block' : 'none';
        info.line.visible = shouldShow;
        return;
      }

      if (enableAdd && state.model && typeof onAddLabelRef.current === 'function') {
        const meshHits = state.raycaster.intersectObjects(state.modelMeshes, true);
        if (meshHits.length > 0) {
          const hit = meshHits[0];
          const worldPoint = hit.point.clone();
          const localPoint = state.model.worldToLocal(worldPoint.clone());

          const normal = hit.face?.normal
            ? hit.face.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(hit.object.matrixWorld)).normalize()
            : new THREE.Vector3(0, 1, 0);

          onAddLabelRef.current({
            worldPosition: worldPoint,
            position: toVecString(localPoint),
            normal: toVecString(normal),
          });
        }
      }
    };

    const onResize = () => {
      const w = container.clientWidth;
      const h = container.clientHeight;
      camera.aspect = w / h;
      camera.updateProjectionMatrix();
      renderer.setSize(w, h);
    };

    const animate = () => {
      state.animationId = requestAnimationFrame(animate);
      controls.update();

      state.labelInfos.forEach(({ element, targetPosition }) => {
        const pos = targetPosition.clone().project(camera);
        if (pos.z < 1 && element.style.display === 'block') {
          const x = (pos.x * 0.5 + 0.5) * container.clientWidth;
          const y = (-pos.y * 0.5 + 0.5) * container.clientHeight;
          element.style.left = `${x - 10}px`;
          element.style.top = `${y - 40}px`;
        } else if (element.style.display === 'block') {
          element.style.display = 'none';
        }
      });

      renderer.render(scene, camera);
    };

    renderer.domElement.addEventListener('click', onClick);
    window.addEventListener('resize', onResize);
    animate();

    return () => {
      cancelAnimationFrame(state.animationId);
      renderer.domElement.removeEventListener('click', onClick);
      window.removeEventListener('resize', onResize);
      controls.dispose();

      clearLabels();

      if (state.model) {
        state.model.traverse((obj: any) => {
          const mesh = obj as THREE.Mesh;
          if (mesh.geometry) mesh.geometry.dispose();
          if (mesh.material) {
            if (Array.isArray(mesh.material)) {
              mesh.material.forEach((mat: THREE.Material) => mat.dispose());
            } else {
              (mesh.material as THREE.Material).dispose();
            }
          }
        });
        scene.remove(state.model);
      }

      if (state.pmremGenerator) {
        state.pmremGenerator.dispose();
      }

      renderer.dispose();
      if (renderer.domElement.parentNode) {
        renderer.domElement.parentNode.removeChild(renderer.domElement);
      }

      state.scene = null;
      state.camera = null;
      state.renderer = null;
      state.controls = null;
      state.model = null;
      state.modelMeshes = [];
    };
  }, [modelUrl, background, showHelpers, enableAdd, exposure, shadowIntensity, cameraControls, touchAction, maxCameraOrbit, environmentImage]);

  useEffect(() => {
    const state = threeRef.current;
    if (!state.scene || !state.model) return;

    const clearLabels = () => {
      state.labelInfos.forEach(({ element, line }) => {
        if (element.parentNode) element.parentNode.removeChild(element);
        line.geometry.dispose();
        if (Array.isArray(line.material)) {
          line.material.forEach((mat: THREE.Material) => mat.dispose());
        } else if (line.material) {
          line.material.dispose();
        }
      });
      state.labelInfos = [];

      state.markers.forEach((m) => {
        m.geometry.dispose();
        if (Array.isArray(m.material)) {
          m.material.forEach((mat: THREE.Material) => mat.dispose());
        } else if (m.material) {
          m.material.dispose();
        }
        state.scene!.remove(m);
      });
      state.markers = [];
    };

    const addLabelPoint = (position: THREE.Vector3, name: string, color: string = '#3399ff', labelOffset: THREE.Vector3, id: string) => {
      const geo = new THREE.SphereGeometry(0.08, 16, 16);
      const mat = new THREE.MeshBasicMaterial({ color });
      const marker = new THREE.Mesh(geo, mat);
      marker.position.copy(position);
      marker.userData = { id, name, isMarker: true };
      state.scene!.add(marker);
      state.markers.push(marker);

      const lineMat = new THREE.LineDashedMaterial({
        color: 0x88ccff,
        linewidth: 2,
        scale: 1,
        dashSize: 0.12,
        gapSize: 0.06,
      });
      const offset = position.clone().add(labelOffset);
      const lineGeo = new THREE.BufferGeometry().setFromPoints([position, offset]);
      const line = new THREE.Line(lineGeo, lineMat);
      line.computeLineDistances();
      line.visible = false;
      state.scene!.add(line);

      const labelDiv = document.createElement('div');
      labelDiv.className = 'anatomy-label';
      const text = document.createElement('span');
      text.textContent = name;
      const close = document.createElement('button');
      close.className = 'close';
      close.type = 'button';
      close.setAttribute('aria-label', 'Close label');
      close.textContent = '×';
      labelDiv.append(text, close);
      labelDiv.style.display = 'none';

      close.onclick = (e) => {
        e.stopPropagation();
        labelDiv.style.display = 'none';
        line.visible = false;
      };

      if (overlayRef.current) overlayRef.current.appendChild(labelDiv);

      state.labelInfos.push({
        element: labelDiv,
        targetPosition: offset,
        marker,
        line,
      });
    };

    clearLabels();
    labelsRef.current.forEach((l) => {
      const localPos = parseVec3(l.position);
      const worldPos = state.model!.localToWorld(localPos.clone());
      addLabelPoint(worldPos, l.title, l.color, state.labelOffset, l.id);
    });
  }, [labels]);

  useEffect(() => {
    const state = threeRef.current;
    if (!state.scene || !state.model) return;

    if (!activeLabelId) return;

    const info = state.labelInfos.find((l) => l.marker.userData.id === activeLabelId);
    if (!info) return;

    state.labelInfos.forEach((item) => {
      const show = item === info;
      item.element.style.display = show ? 'block' : 'none';
      item.line.visible = show;
    });
  }, [activeLabelId]);

  // ...existing code for previewPosition useEffect...
  useEffect(() => {
    const state = threeRef.current;
    if (!state.scene || !state.model) return;

    if (!previewPosition) {
      if (state.previewMarker) state.previewMarker.visible = false;
      return;
    }

    const localPos = parseVec3(previewPosition);
    const worldPos = state.model.localToWorld(localPos.clone());

    if (!state.previewMarker) {
      const geo = new THREE.SphereGeometry(0.09, 18, 18);
      const mat = new THREE.MeshBasicMaterial({ color: 0xf97316 });
      state.previewMarker = new THREE.Mesh(geo, mat);
      state.scene.add(state.previewMarker);
    }

    state.previewMarker.position.copy(worldPos);
    state.previewMarker.visible = true;
  }, [previewPosition]);

  return (
    <div className={`viewer-root ${enableAdd ? 'is-adding' : ''}`} role="img" aria-label={alt}>
      <div className="actions">  
        <Button onClick={onClose} className="btn-close" size='small' color='error' variant="outlined" sx={{background:'#a10303', color:'#fff'}}>X</Button>
      </div>
      <div className="viewer-canvas" ref={containerRef} style={{ touchAction }} />
      <div className="viewer-overlay" ref={overlayRef} />
      {loading && (
        <Box className="viewer-loader" >
          <div><CircularProgress variant='indeterminate'  /></div>
          <p>Loading Preview</p>
        </Box>
      )}
      <div className="viewer-hint">Click on annotation hotspots to view details</div>
      {!loading && <TextToSpeech
        text={speachtext}
        rate={1}
        pitch={1}
        lang="en-US"
      />}
    </div>
  );
}