"use client";

import { useRef, useEffect, useState } from "react";
import { Canvas, useFrame, useLoader } from "@react-three/fiber";
import { Center, OrbitControls, useTexture } from "@react-three/drei";
import * as THREE from "three";

// Individual Food Plate 3D Component
function FoodPlate({ activeIdx, isHovered }: { activeIdx: number; isHovered: boolean }) {
  const plateRef = useRef<THREE.Group>(null);
  
  // Load food textures dynamically
  const textures = [
    useTexture("/images/masala_dosa_luxury.png"),
    useTexture("/images/south_indian_thali_luxury.png"),
  ];

  // Store target rotation/position for smooth spring interpolation
  const targetRotationY = useRef(0);
  const targetPositionY = useRef(0);
  const targetScale = useRef(1);

  useFrame((state) => {
    if (!plateRef.current) return;

    // 1. Continuous slow rotation
    targetRotationY.current += 0.005;

    // 2. Mouse interactive tilt effect
    const mouseX = state.pointer.x * 0.4;
    const mouseY = state.pointer.y * 0.4;
    
    plateRef.current.rotation.x = THREE.MathUtils.lerp(plateRef.current.rotation.x, 0.65 - mouseY, 0.1);
    plateRef.current.rotation.y = THREE.MathUtils.lerp(plateRef.current.rotation.y, targetRotationY.current + mouseX, 0.1);
    
    // 3. Hover lift effect & slow float oscillation
    const hoverOffset = isHovered ? 0.3 : 0;
    const floatOffset = Math.sin(state.clock.getElapsedTime() * 1.5) * 0.08;
    targetPositionY.current = hoverOffset + floatOffset;
    plateRef.current.position.y = THREE.MathUtils.lerp(plateRef.current.position.y, targetPositionY.current, 0.08);

    // Scale spring transition
    targetScale.current = isHovered ? 1.08 : 1.0;
    plateRef.current.scale.setScalar(
      THREE.MathUtils.lerp(plateRef.current.scale.x, targetScale.current, 0.1)
    );
  });

  return (
    <group ref={plateRef} rotation={[0.65, 0, 0]} position={[0, -0.2, 0]}>
      {/* 1. Base Brass Plate */}
      <mesh castShadow receiveShadow>
        <cylinderGeometry args={[2.5, 2.3, 0.18, 64]} />
        <meshPhysicalMaterial
          color="#D4AF37"
          metalness={0.9}
          roughness={0.18}
          clearcoat={1.0}
          clearcoatRoughness={0.1}
          reflectivity={1.0}
        />
      </mesh>
      
      {/* Brass Rim/lip details */}
      <mesh position={[0, 0.1, 0]}>
        <torusGeometry args={[2.45, 0.08, 16, 100]} />
        <meshStandardMaterial color="#AA7C11" metalness={0.95} roughness={0.15} />
      </mesh>

      {/* 2. Banana Leaf Liner */}
      <mesh position={[0, 0.1, 0]}>
        <cylinderGeometry args={[2.35, 2.35, 0.02, 64]} />
        <meshStandardMaterial
          color="#1e5128"
          roughness={0.8}
          bumpScale={0.05}
        />
      </mesh>

      {/* 3. Photorealistic Food Mesh with texture projection */}
      <mesh position={[0, 0.12, 0]}>
        <cylinderGeometry args={[2.25, 2.25, 0.01, 64]} />
        <meshStandardMaterial
          map={textures[activeIdx]}
          roughness={0.4}
          metalness={0.0}
        />
      </mesh>
    </group>
  );
}

// Spices / Ingredients flying around the plate
function FloatingIngredients({ activeIdx }: { activeIdx: number }) {
  const count = 18;
  const meshRef = useRef<THREE.Group>(null);
  const particles = useRef<Array<{
    pos: THREE.Vector3;
    speed: THREE.Vector3;
    rot: THREE.Vector3;
    rotSpeed: THREE.Vector3;
    scale: number;
    color: string;
  }>>([]);

  useEffect(() => {
    // Generate random ingredients positions and velocities
    const temp: typeof particles.current = [];
    for (let i = 0; i < count; i++) {
      const isCurryLeaf = i % 3 === 0;
      const isRedChili = i % 3 === 1;
      
      temp.push({
        pos: new THREE.Vector3(
          (Math.random() - 0.5) * 8,
          (Math.random() - 0.5) * 6 + 2,
          (Math.random() - 0.5) * 4
        ),
        speed: new THREE.Vector3(
          (Math.random() - 0.5) * 0.02,
          -Math.random() * 0.015 - 0.005,
          (Math.random() - 0.5) * 0.01
        ),
        rot: new THREE.Vector3(Math.random() * Math.PI, Math.random() * Math.PI, 0),
        rotSpeed: new THREE.Vector3(Math.random() * 0.02, Math.random() * 0.02, 0),
        scale: isCurryLeaf ? 0.25 : isRedChili ? 0.12 : 0.05,
        color: isCurryLeaf ? "#2E7D32" : isRedChili ? "#D84315" : "#212121", // Green, Red, Black (mustard seeds)
      });
    }
    particles.current = temp;
  }, [activeIdx]);

  useFrame(() => {
    if (!meshRef.current) return;
    
    // Animate flying items
    const children = meshRef.current.children;
    particles.current.forEach((p, idx) => {
      const child = children[idx] as THREE.Mesh;
      if (!child) return;

      // Update position
      p.pos.add(p.speed);
      p.rot.add(p.rotSpeed);

      // Magnet effect: pull slightly towards center plate [0, 0, 0]
      const toCenter = new THREE.Vector3(0, 0, 0).sub(p.pos);
      p.speed.add(toCenter.multiplyScalar(0.0002));

      // Speed limits
      p.speed.clampLength(0.005, 0.04);

      // Boundaries wrap-around
      if (p.pos.y < -4) {
        p.pos.y = 4;
        p.pos.x = (Math.random() - 0.5) * 6;
      }
      if (p.pos.x < -6) p.pos.x = 6;
      if (p.pos.x > 6) p.pos.x = -6;

      child.position.copy(p.pos);
      child.rotation.set(p.rot.x, p.rot.y, p.rot.z);
    });
  });

  return (
    <group ref={meshRef}>
      {Array.from({ length: count }).map((_, idx) => {
        const isCurryLeaf = idx % 3 === 0;
        const isRedChili = idx % 3 === 1;

        if (isCurryLeaf) {
          // Curved plane for Curry Leaf
          return (
            <mesh key={idx}>
              <boxGeometry args={[0.6, 0.3, 0.02]} />
              <meshStandardMaterial color="#1B5E20" roughness={0.7} />
            </mesh>
          );
        } else if (isRedChili) {
          // Cylinder for chili pod
          return (
            <mesh key={idx}>
              <cylinderGeometry args={[0.08, 0.08, 0.4, 8]} />
              <meshStandardMaterial color="#C62828" roughness={0.5} />
            </mesh>
          );
        } else {
          // Sphere for Mustard Seed
          return (
            <mesh key={idx}>
              <sphereGeometry args={[0.08, 8, 8]} />
              <meshStandardMaterial color="#1a0f05" roughness={0.9} metalness={0.1} />
            </mesh>
          );
        }
      })}
    </group>
  );
}

// Steam Particles rising from plate
function SteamEffect() {
  const count = 15;
  const groupRef = useRef<THREE.Group>(null);
  const steamParticles = useRef<Array<{
    pos: THREE.Vector3;
    speedY: number;
    speedX: number;
    opacity: number;
    scale: number;
  }>>([]);

  useEffect(() => {
    const temp: typeof steamParticles.current = [];
    for (let i = 0; i < count; i++) {
      temp.push({
        pos: new THREE.Vector3(
          (Math.random() - 0.5) * 1.5,
          Math.random() * 2 + 0.2,
          (Math.random() - 0.5) * 1.5
        ),
        speedY: Math.random() * 0.015 + 0.008,
        speedX: (Math.random() - 0.5) * 0.006,
        opacity: Math.random() * 0.3 + 0.1,
        scale: Math.random() * 0.3 + 0.2,
      });
    }
    steamParticles.current = temp;
  }, []);

  useFrame(() => {
    if (!groupRef.current) return;
    const children = groupRef.current.children;
    steamParticles.current.forEach((p, idx) => {
      const child = children[idx] as THREE.Mesh;
      if (!child) return;

      p.pos.y += p.speedY;
      p.pos.x += p.speedX;
      p.opacity -= 0.0018; // Fade out as it rises

      // Reset when faded or high
      if (p.pos.y > 3.0 || p.opacity <= 0) {
        p.pos.y = Math.random() * 0.2 + 0.15;
        p.pos.x = (Math.random() - 0.5) * 1.2;
        p.opacity = Math.random() * 0.3 + 0.1;
      }

      child.position.copy(p.pos);
      child.scale.setScalar(p.scale * (1 + p.pos.y * 0.5)); // expand as it rises
      
      const mat = child.material as THREE.MeshBasicMaterial;
      if (mat) {
        mat.opacity = p.opacity;
      }
    });
  });

  return (
    <group ref={groupRef}>
      {Array.from({ length: count }).map((_, idx) => (
        <mesh key={idx}>
          <sphereGeometry args={[0.3, 16, 16]} />
          <meshBasicMaterial
            color="#EFEBE9"
            transparent
            opacity={0.1}
            blending={THREE.AdditiveBlending}
            depthWrite={false}
          />
        </mesh>
      ))}
    </group>
  );
}

export default function FoodCanvas({ activeIdx, isHovered }: { activeIdx: number; isHovered: boolean }) {
  return (
    <div className="w-full h-full relative">
      <Canvas
        shadows
        camera={{ position: [0, 2.2, 5.0], fov: 45 }}
        gl={{ antialias: true, alpha: true }}
      >
        <ambientLight intensity={1.5} color="#F5F0E6" />
        
        {/* Spotlight shining on plate for royal gold reflections */}
        <spotLight
          position={[5, 10, 5]}
          angle={0.3}
          penumbra={1}
          intensity={50}
          castShadow
          shadow-bias={-0.0001}
          color="#D4AF37"
        />

        <directionalLight position={[-5, 5, -5]} intensity={1.5} color="#AA7C11" />
        <pointLight position={[0, -2, 2]} intensity={2.0} color="#6C1E27" />

        <Center>
          <FoodPlate activeIdx={activeIdx} isHovered={isHovered} />
          <SteamEffect />
          <FloatingIngredients activeIdx={activeIdx} />
        </Center>

        <OrbitControls
          enableZoom={false}
          enablePan={false}
          maxPolarAngle={Math.PI / 2 - 0.05} // prevent going below table
          minPolarAngle={Math.PI / 6}
        />
      </Canvas>
    </div>
  );
}
