import { useRef, useMemo } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { BufferGeometry, Material, MathUtils, Mesh } from "three";
import { vertexShader } from "./Shaders/Background/vertex";
import { fragmentShader } from "./Shaders/Background/fragment";

const Fragment = () => {
  // This reference will give us direct access to the mesh
  const meshRef = useRef<Mesh<BufferGeometry, Material | Material[]>>(null);

  const uniforms = useMemo(
    () => ({
      u_intensity: {
        value: 1.0,
      },
      u_time: {
        value: 0.0,
      },
    }),
    []
  );

  useFrame((state) => {
    if (!meshRef.current) {
      return;
    }
    const { clock } = state;
    //@ts-ignore
    meshRef.current.material.uniforms.u_time.value =
      (0.4 * clock.getElapsedTime()) / 5;
    //@ts-ignore
    meshRef.current.material.uniforms.u_intensity.value = MathUtils.lerp(
      //@ts-ignore
      meshRef.current.material.uniforms.u_intensity.value,
      1.0,
      0.02
    );
  });

  return (
    <mesh
      ref={meshRef}
      position={[0, 0, 0]}
      rotation={[-Math.PI / 17, Math.PI / 20, 0]}
      scale={1.5}
    >
      <planeGeometry args={[30, 30, 200, 200]} />
      <shaderMaterial
        fragmentShader={fragmentShader}
        vertexShader={vertexShader}
        uniforms={uniforms}
        wireframe={false}
      />
    </mesh>
  );
};

export const R3Gradient = () => {
  return (
    <div className="-z-40 h-screen w-screen fixed bg-black opacity-60 top-0 left-0">
      <Canvas camera={{ position: [0.0, 0.0, 5.0] }}>
        <Fragment />
      </Canvas>
    </div>
  );
};
