import { useMemo } from 'react';
import * as THREE from 'three';

export interface WindArrowProps {
  /** Ponto onde a ponta da seta do vento toca (ex: centro geométrico da estrutura) */
  target: THREE.Vector3 | [number, number, number];
  /** Direção de onde o vento vem (e para onde ele vai). Vetor normalizado. */
  direction: THREE.Vector3 | [number, number, number];
  /** Fator de escala da seta (default: 1) */
  scale?: number;
}

export function WindArrow({ target, direction, scale = 1 }: WindArrowProps) {
  const length = 2.5 * scale; // Tamanho visual fixo
  const color = '#3b82f6'; // Azul padrão do vento

  const targetVec = target instanceof THREE.Vector3 ? target : new THREE.Vector3(...target);
  const dirVec = direction instanceof THREE.Vector3 ? direction : new THREE.Vector3(...direction);

  const end = targetVec;
  const base = useMemo(
    () => new THREE.Vector3(end.x - dirVec.x * length, end.y - dirVec.y * length, end.z - dirVec.z * length),
    [end, dirVec, length],
  );

  const headLen = 0.3 * scale;
  const headRadius = 0.1 * scale;
  const shaftRadius = 0.04 * scale;

  const midPoint = useMemo(
    () => new THREE.Vector3((base.x + end.x) / 2, (base.y + end.y) / 2, (base.z + end.z) / 2),
    [base, end],
  );
  const shaftLength = length - headLen;

  const rotation = useMemo(() => {
    const dir = new THREE.Vector3().subVectors(end, base).normalize();
    const quat = new THREE.Quaternion();
    quat.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir);
    const euler = new THREE.Euler().setFromQuaternion(quat);
    return [euler.x, euler.y, euler.z] as [number, number, number];
  }, [base, end]);

  return (
    <group>
      {shaftLength > 0 && (
        <mesh position={midPoint.toArray()} rotation={rotation} castShadow>
          <cylinderGeometry args={[shaftRadius, shaftRadius, shaftLength, 12]} />
          <meshStandardMaterial color={color} />
        </mesh>
      )}
      {/* Ponta da seta (cone) */}
      <mesh position={[end.x, end.y, end.z]} rotation={rotation} castShadow>
        <coneGeometry args={[headRadius, headLen, 12]} />
        <meshStandardMaterial color={color} />
      </mesh>
    </group>
  );
}
