"use client";

import { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import NavbarLayoutFloatingOverlay from '@/components/navbar/NavbarLayoutFloatingOverlay/NavbarLayoutFloatingOverlay';
import { ContactSplitForm } from '@/components/sections/contact/ContactSplitForm';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import { Phone } from "lucide-react";

export default function Gym3DPage() {
  const containerRef = useRef<HTMLDivElement>(null);
  const sceneRef = useRef<THREE.Scene | null>(null);
  const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
  const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (!containerRef.current) return;

    // Scene setup
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x0a0a0a);
    sceneRef.current = scene;

    // Camera setup
    const camera = new THREE.PerspectiveCamera(
      75,
      containerRef.current.clientWidth / containerRef.current.clientHeight,
      0.1,
      1000
    );
    camera.position.set(0, 10, 20);
    camera.lookAt(0, 5, 0);
    cameraRef.current = camera;

    // Renderer setup
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(containerRef.current.clientWidth, containerRef.current.clientHeight);
    renderer.shadowMap.enabled = true;
    containerRef.current.appendChild(renderer.domElement);
    rendererRef.current = renderer;

    // Lighting
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
    scene.add(ambientLight);

    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(10, 15, 10);
    directionalLight.castShadow = true;
    directionalLight.shadow.mapSize.width = 2048;
    directionalLight.shadow.mapSize.height = 2048;
    scene.add(directionalLight);

    // Ground/Floor
    const groundGeometry = new THREE.PlaneGeometry(40, 40);
    const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x1a1a1a });
    const ground = new THREE.Mesh(groundGeometry, groundMaterial);
    ground.rotation.x = -Math.PI / 2;
    ground.receiveShadow = true;
    scene.add(ground);

    // Gym Equipment - Power Rack
    const rackGeometry = new THREE.BoxGeometry(2, 3, 1.5);
    const rackMaterial = new THREE.MeshStandardMaterial({ color: 0x333333, metalness: 0.8 });
    const rack = new THREE.Mesh(rackGeometry, rackMaterial);
    rack.position.set(-8, 1.5, 0);
    rack.castShadow = true;
    scene.add(rack);

    // Barbell
    const barbellGeometry = new THREE.CylinderGeometry(0.02, 0.02, 2.2, 16);
    const barbellMaterial = new THREE.MeshStandardMaterial({ color: 0xffff00, metalness: 1 });
    const barbell = new THREE.Mesh(barbellGeometry, barbellMaterial);
    barbell.position.set(-8, 1.8, 0);
    barbell.rotation.z = Math.PI / 2;
    barbell.castShadow = true;
    scene.add(barbell);

    // Weight plates on barbell
    for (let i = 0; i < 4; i++) {
      const plateGeometry = new THREE.CylinderGeometry(0.5, 0.5, 0.05, 32);
      const plateMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000, metalness: 0.6 });
      const plate = new THREE.Mesh(plateGeometry, plateMaterial);
      plate.position.set(-8 + (i - 1.5) * 0.6, 1.8, 0);
      plate.castShadow = true;
      scene.add(plate);
    }

    // Dumbbells rack
    for (let i = 0; i < 5; i++) {
      const dumbellGeometry = new THREE.CylinderGeometry(0.15, 0.15, 0.5, 16);
      const dumbellMaterial = new THREE.MeshStandardMaterial({ color: 0xffaa00, metalness: 0.7 });
      const dumbell = new THREE.Mesh(dumbellGeometry, dumbellMaterial);
      dumbell.position.set(0 + i * 1.5, 0.5, -10);
      dumbell.castShadow = true;
      scene.add(dumbell);
    }

    // Gymnastics Rig
    const rigGeometry = new THREE.BoxGeometry(0.1, 0.1, 5);
    const rigMaterial = new THREE.MeshStandardMaterial({ color: 0x333333, metalness: 0.8 });
    const rig = new THREE.Mesh(rigGeometry, rigMaterial);
    rig.position.set(0, 8, 0);
    rig.castShadow = true;
    scene.add(rig);

    // Olympic Rings
    const ringRadius = 0.3;
    const ringPositions = [-1.2, -0.4, 0.4, 1.2];
    ringPositions.forEach((x) => {
      const torusGeometry = new THREE.TorusGeometry(ringRadius, 0.08, 16, 100);
      const torusMaterial = new THREE.MeshStandardMaterial({ color: 0xffffff, metalness: 0.9 });
      const ring = new THREE.Mesh(torusGeometry, torusMaterial);
      ring.position.set(x, 7, 0);
      ring.rotation.x = Math.PI / 5;
      ring.castShadow = true;
      scene.add(ring);
    });

    // Rowing Machine
    const rowingGeometry = new THREE.BoxGeometry(0.8, 1, 2.5);
    const rowingMaterial = new THREE.MeshStandardMaterial({ color: 0x222222, metalness: 0.6 });
    const rowingMachine = new THREE.Mesh(rowingGeometry, rowingMaterial);
    rowingMachine.position.set(8, 0.8, -5);
    rowingMachine.castShadow = true;
    scene.add(rowingMachine);

    // Treadmill
    const treadmillGeometry = new THREE.BoxGeometry(1, 1.2, 2);
    const treadmillMaterial = new THREE.MeshStandardMaterial({ color: 0x1a1a1a, metalness: 0.5 });
    const treadmill = new THREE.Mesh(treadmillGeometry, treadmillMaterial);
    treadmill.position.set(8, 0.8, 0);
    treadmill.castShadow = true;
    scene.add(treadmill);

    // Kettlebells
    for (let i = 0; i < 3; i++) {
      const kettlebellGeometry = new THREE.SphereGeometry(0.4, 16, 16);
      const kettlebellMaterial = new THREE.MeshStandardMaterial({ color: 0x333333, metalness: 0.7 });
      const kettlebell = new THREE.Mesh(kettlebellGeometry, kettlebellMaterial);
      kettlebell.position.set(-10, 0.6, -5 + i * 2);
      kettlebell.castShadow = true;
      scene.add(kettlebell);
    }

    // Battle Ropes anchor
    const ropeAnchorGeometry = new THREE.BoxGeometry(0.2, 3, 0.2);
    const ropeAnchorMaterial = new THREE.MeshStandardMaterial({ color: 0x444444, metalness: 0.8 });
    const ropeAnchor = new THREE.Mesh(ropeAnchorGeometry, ropeAnchorMaterial);
    ropeAnchor.position.set(0, 2, 10);
    ropeAnchor.castShadow = true;
    scene.add(ropeAnchor);

    // Walls
    const wallGeometry = new THREE.BoxGeometry(40, 5, 0.5);
    const wallMaterial = new THREE.MeshStandardMaterial({ color: 0x0f0f0f });
    
    const wallBack = new THREE.Mesh(wallGeometry, wallMaterial);
    wallBack.position.set(0, 2.5, -20);
    wallBack.receiveShadow = true;
    scene.add(wallBack);

    // Loading complete
    setIsLoading(false);

    // Animation loop
    const animate = () => {
      requestAnimationFrame(animate);

      // Rotate dumbbells slightly
      scene.children.forEach((child) => {
        if (child instanceof THREE.Mesh && child.geometry instanceof THREE.CylinderGeometry) {
          if (child.position.z === -10) {
            child.rotation.x += 0.01;
          }
        }
      });

      // Rotate camera slightly
      const time = Date.now() * 0.0005;
      camera.position.x = Math.sin(time) * 25;
      camera.position.z = Math.cos(time) * 25;
      camera.lookAt(0, 5, 0);

      renderer.render(scene, camera);
    };
    animate();

    // Handle window resize
    const handleResize = () => {
      if (!containerRef.current) return;
      const width = containerRef.current.clientWidth;
      const height = containerRef.current.clientHeight;
      camera.aspect = width / height;
      camera.updateProjectionMatrix();
      renderer.setSize(width, height);
    };
    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
      containerRef.current?.removeChild(renderer.domElement);
    };
  }, []);

  return (
    <ThemeProvider
      defaultButtonVariant="text-shift"
      defaultTextAnimation="reveal-blur"
      borderRadius="pill"
      contentWidth="medium"
      sizing="largeSmallSizeMediumTitles"
      background="circleGradient"
      cardStyle="gradient-bordered"
      primaryButtonStyle="primary-glow"
      secondaryButtonStyle="radial-glow"
      headingFontWeight="normal"
    >
      <div id="nav" data-section="nav">
        <NavbarLayoutFloatingOverlay
          brandName="Iron Pulse"
          navItems={[
            { name: "WOD", id: "wod" },
            { name: "Pricing", id: "pricing" },
            { name: "Gallery", id: "gallery" },
            { name: "Testimonials", id: "testimonials" },
            { name: "Home", id: "/" }
          ]}
          button={{ text: "Start Your Trial", href: "contact" }}
        />
      </div>

      <div className="w-full h-screen bg-background" ref={containerRef}>
        {isLoading && (
          <div className="absolute inset-0 flex items-center justify-center bg-background/80 backdrop-blur-sm">
            <div className="text-center">
              <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-primary-cta"></div>
              <p className="text-foreground mt-4">Loading 3D Gym Tour...</p>
            </div>
          </div>
        )}
      </div>

      <div id="contact" data-section="contact" className="py-20">
        <ContactSplitForm
          title="Interested in joining Iron Pulse?"
          description="Fill out the form below and our coaching team will reach out within 24 hours to schedule your trial session."
          inputs={[
            { name: "name", type: "text", placeholder: "Full Name", required: true },
            { name: "email", type: "email", placeholder: "Email Address", required: true }
          ]}
          textarea={{
            name: "message",            placeholder: "Tell us about your fitness goals and experience level...",            rows: 5,
            required: false
          }}
          useInvertedBackground={false}
          mediaAnimation="slide-up"
          buttonText="Schedule Trial"
          onSubmit={(data) => {
            console.log("Form submitted:", data);
            alert("Thank you for reaching out! We'll contact you soon.");
          }}
          ariaLabel="Contact form section"
        />
      </div>
    </ThemeProvider>
  );
}