"use client";

/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useRef, useState } from "react";
import type { Hotspot } from "./types";
import TextToSpeech from './TextToSpeech';
import './Model3DViewer.model.css'
import type { ModelViewerElement } from "@google/model-viewer";
import { Chip } from "@mui/material";

interface Model3DViewerProps {
  src: string;
  alt?: string;
  title?: string;
  speachtext?: string;
  hotspots?: Hotspot[];
  autoRotate?: boolean;
  cameraControls?: boolean;
  style?: React.CSSProperties;
  onClose?: () => void
}


const Model3DViewer: React.FC<Model3DViewerProps> = ({
  src,
  alt = "3D model",
  hotspots = [],
  speachtext="",
  title="",
  style,
  onClose
}) => {
  const modelRef = useRef<ModelViewerElement | null>(null);

  const [activeHotspot, setActiveHotspot] = useState<string | null>(null);
  // const [progress, setProgress] = useState<number>(0);
  // const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isRendered, setIsRendered] = useState(false);

  // Dynamically import @google/model-viewer on client-side only
  useEffect(() => {
    import("@google/model-viewer").catch((err) => console.error("Failed to load model-viewer:", err));
  }, []);

  useEffect(() => {
    const model = modelRef.current;
    if (!model) return;

    // Fires when model finishes loading
    const handleLoad = () => {
      // Wait for next frame to ensure render
      requestAnimationFrame(() => {
        setIsRendered(true);
      });
    };

    model.addEventListener("load", handleLoad);

    return () => {
      model.removeEventListener("load", handleLoad);
    };
  }, []);
  

  const handleModelClick = (event:any) => {
  const model = modelRef.current;
  if (!model) return;

  const rect = model.getBoundingClientRect();

  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;

  // Get 3D position + normal
  const hit = model.positionAndNormalFromPoint(x, y);

  if (hit) {
    const position = hit.position.toString(); // "x y z"
    const normal = hit.normal.toString();     // "nx ny nz"

    console.log("data-position:", position);
    console.log("data-normal:", normal);

    // You can now store it in state
    // addHotspot(position, normal);
  }
};

useEffect(() => {
  const model = modelRef.current;
  if (!model) return;

  model.addEventListener("click", handleModelClick);

  return () => {
    model.removeEventListener("click", handleModelClick);
  };
}, []);

  return (
    <div
      style={{ position: "relative", width: "100%", height: "100%", background:"#0a0e1a", ...style }}
    >
      {!isRendered && (
        <div className="loader-overlay">
          <div className="loader">
            <div className="spinner" />
            <p>Loading Preview...</p>
          </div>
        </div>
      )}
      <div className="annotation">  Click on annotation hotspots to view details </div>
      {/* @ts-expect-error custom web component */}
      <model-viewer
        ref={modelRef}
        src={src}
        alt={alt}
        debug-hotspots="true"
        camera-controls="true"
        interaction-prompt-threshold="0"
        shadow-intensity="0.5"
        shadow-softness="0.5"
        exposure="1"
        environment-image="neutral"
        loading="eager"
        reveal="auto"
        touch-action="pan-y"
        crossorigin="anonymous"
        max-camera-orbit="auto 90deg auto"
        //   min-camera-orbit="auto 0deg auto"
        //   ar-status="not-presenting"
        style={{ width: "100%", height: "100%", cursor: "default" }}
      >
          <div className="preview-mode">  Preview Mode</div>
          <div className="actions">  
            <button onClick={onClose} className="btn-close">X</button>
          </div>
          
        {isRendered && hotspots.map((hotspot) => {
          const isActive = activeHotspot === hotspot.id;

          return (
            <div
              key={hotspot.id}
              slot={`hotspot-${hotspot.id}`}
              data-position={hotspot.position}
              data-normal={hotspot.normal}
              className="hotspot-wrapper"
            >
              {/* Tooltip LEFT */}
              {isActive && (
                <div className="hotspot-container">
                  {/* <div className="hotspot-tooltip">
                    <div className="tooltip-header">
                      <span>{hotspot.title}</span>
                      <button
                        className="close-btn"
                        onClick={() => setActiveHotspot(null)}
                      >
                        ✕
                      </button>
                    </div>
                  </div> */}
                  <Chip label={hotspot.title} variant="outlined" 
                    onDelete={() => setActiveHotspot(null)} 
                    sx={{background:'#fff'}}
                  />

                  {/* Horizontal line */}
                  <div className="hotspot-line" />
                </div>
              )}

              {/* Hotspot Dot */}
              <button
                className="hotspot-dot"
                onClick={() =>
                  setActiveHotspot(isActive ? null : hotspot.id)
                }
              />
            </div>
          );
        })}
      {/* @ts-expect-error custom web component */}
      </model-viewer>
      {isRendered && speachtext != "" && <TextToSpeech
        text={speachtext}
        rate={1}
        pitch={1}
        lang="en-US"
        title={title}
    />}

    </div>
  );
};

export default Model3DViewer;
