import React, { useRef } from 'react'
import { Canvas, useFrame, useLoader } from '@react-three/fiber'
import { OrbitControls, Stars } from '@react-three/drei'
import { EffectComposer, Bloom } from '@react-three/postprocessing'
import * as THREE from 'three'
import { TextureLoader } from 'three'

// Import tekstur planet i słońca (upewnij się, że pliki znajdują się w katalogu src/assets)
import mercuryTextureUrl from './assets/mercury.png'
import venusTextureUrl from './assets/venus.png'
import earthTextureUrl from './assets/earth.png'
import marsTextureUrl from './assets/mars.webp'
import jupiterTextureUrl from './assets/jupiter.png'
import saturnTextureUrl from './assets/saturn.png'
import uranusTextureUrl from './assets/uranus.png'
import neptuneTextureUrl from './assets/neptune.webp'
import sunTextureUrl from './assets/sun.png'

// Komponent reprezentujący pojedynczą planetę (można podać opcjonalnie teksturę)
function Planet({ orbitRadius, size, speed, rotationSpeed = 0.5, color, texture }) {
  const mesh = useRef()
  useFrame((state, delta) => {
    const elapsed = state.clock.elapsedTime
    if (mesh.current) {
      // Ruch po orbitach w płaszczyźnie XZ
      mesh.current.position.x = orbitRadius * Math.cos(speed * elapsed)
      mesh.current.position.z = orbitRadius * Math.sin(speed * elapsed)
      // Obrót planety wokół własnej osi
      mesh.current.rotation.y += rotationSpeed * delta
    }
  })

  return (
    <mesh ref={mesh}>
      <sphereGeometry args={[size, 32, 32]} />
      {texture ? (
         <meshStandardMaterial 
            map={useLoader(TextureLoader, texture)}
            emissiveMap={useLoader(TextureLoader, texture)}
            emissiveIntensity={0.2}
         />
      ) : (
         <meshStandardMaterial color={color} emissive={color} emissiveIntensity={0.5} />
      )}
    </mesh>
  )
}

// Specjalny komponent dla Saturna z pierścieniem (tekstura dla kuli jest opcjonalna)
function Saturn({ orbitRadius, size, speed, rotationSpeed = 0.5, color, texture }) {
  const group = useRef()
  useFrame((state, delta) => {
    const elapsed = state.clock.elapsedTime
    if (group.current) {
      group.current.position.x = orbitRadius * Math.cos(speed * elapsed)
      group.current.position.z = orbitRadius * Math.sin(speed * elapsed)
      group.current.rotation.y += rotationSpeed * delta
    }
  })

  return (
    <group ref={group}>
      <mesh>
        <sphereGeometry args={[size, 32, 32]} />
        {texture ? (
           <meshStandardMaterial 
             map={useLoader(TextureLoader, texture)}
             emissiveMap={useLoader(TextureLoader, texture)}
             emissiveIntensity={0.2}
           />
         ) : (
           <meshStandardMaterial color={color} emissive={color} emissiveIntensity={0.5} />
         )}
      </mesh>
      {/* Pierścień Saturna */}
      <mesh rotation={[Math.PI / 2, 0, 0]}>
        <ringGeometry args={[size * 1.2, size * 1.8, 32]} />
        <meshBasicMaterial
          color={0xaaaaaa}
          side={THREE.DoubleSide}
          transparent
          opacity={0.6}
        />
      </mesh>
    </group>
  )
}

// Nowy komponent Słońca z teksturą i efektem emisji
function Sun({ size }) {
  const sunTexture = useLoader(TextureLoader, sunTextureUrl)
  return (
    <mesh>
      <sphereGeometry args={[size, 32, 32]} />
      <meshStandardMaterial 
         map={sunTexture}
         emissive={0xffaa00}
         emissiveIntensity={1.5}
      />
    </mesh>
  )
}

// Komponent do rysowania trajektorii orbity
function OrbitTrajectory({ orbitRadius }) {
  const points = []
  const segments = 64
  for (let i = 0; i <= segments; i++) {
    const theta = (i / segments) * Math.PI * 2
    points.push(Math.cos(theta) * orbitRadius, 0, Math.sin(theta) * orbitRadius)
  }
  return (
    <line>
      <bufferGeometry attach="geometry">
        <bufferAttribute 
          attachObject={['attributes', 'position']} 
          count={points.length / 3} 
          array={new Float32Array(points)} 
          itemSize={3} 
        />
      </bufferGeometry>
      <lineBasicMaterial attach="material" color="#ffffff" />
    </line>
  )
}

export default function SolarSystem() {
  return (
    <Canvas 
      camera={{ position: [0, 30, 50], fov: 60 }} 
      style={{ width: "100vw", height: "100vh" }}
    >
      {/* Ustawienie czarnego tła */}
      <color attach="background" args={["#202020"]} />
      
      <ambientLight intensity={0.2} />
      
      {/* Dodanie gwiezdnego tła */}
      <Stars radius={100} depth={50} count={2000} factor={4} saturation={0} fade />
      
      {/* Słońce jako punktowe źródło światła */}
      <pointLight intensity={2} position={[0, 0, 0]} />
 
      {/* Słońce - wyróżnione jako jasna kula */}
      <Sun size={3} />
 
      {/* Trajektorie planet */}
      <OrbitTrajectory orbitRadius={8} />
      <OrbitTrajectory orbitRadius={11} />
      <OrbitTrajectory orbitRadius={14} />
      <OrbitTrajectory orbitRadius={17} />
      <OrbitTrajectory orbitRadius={22} />
      <OrbitTrajectory orbitRadius={27} />
      <OrbitTrajectory orbitRadius={32} />
      <OrbitTrajectory orbitRadius={37} />
 
      {/* Planety */}
      <Planet orbitRadius={8} size={0.5} speed={1.2} texture={mercuryTextureUrl} rotationSpeed={1} />           {/* Merkury */}
      <Planet orbitRadius={11} size={0.7} speed={0.9} texture={venusTextureUrl} rotationSpeed={0.8} />          {/* Wenus */}
      <Planet orbitRadius={14} size={0.75} speed={0.8} texture={earthTextureUrl} rotationSpeed={1} />           {/* Ziemia */}
      <Planet orbitRadius={17} size={0.6} speed={0.7} texture={marsTextureUrl} rotationSpeed={1} />           {/* Mars */}
      <Planet orbitRadius={22} size={1.5} speed={0.5} texture={jupiterTextureUrl} rotationSpeed={1} />            {/* Jowisz */}
      <Saturn orbitRadius={27} size={1.3} speed={0.4} texture={saturnTextureUrl} rotationSpeed={1} />             {/* Saturn */}
      <Planet orbitRadius={32} size={1} speed={0.3} texture={uranusTextureUrl} rotationSpeed={1} />              {/* Uran */}
      <Planet orbitRadius={37} size={1} speed={0.28} texture={neptuneTextureUrl} rotationSpeed={1} />             {/* Neptun */}
 
      {/* Umożliwienie interaktywnego obracania sceny */}
      <OrbitControls />
      <EffectComposer>
         <Bloom intensity={1.2} luminanceThreshold={0.3} luminanceSmoothing={0.75} height={300} />
      </EffectComposer>
    </Canvas>
  )
} 