'use client'

import { useRef, useMemo } from 'react'
import { useFrame } from '@react-three/fiber'
import { Environment, MeshReflectorMaterial } from '@react-three/drei'
import * as THREE from 'three'
import type { ClubData } from '@/types'

function createJerseyTexture(primaryColor: string, secondaryColor: string, number: number, name: string): THREE.CanvasTexture {
  const canvas = document.createElement('canvas')
  canvas.width = 512
  canvas.height = 512
  const ctx = canvas.getContext('2d')!

  // Jersey base
  ctx.fillStyle = primaryColor
  ctx.fillRect(0, 0, 512, 512)

  // Collar area
  ctx.fillStyle = secondaryColor
  ctx.beginPath()
  ctx.ellipse(256, 80, 70, 40, 0, 0, Math.PI * 2)
  ctx.fill()

  // Vertical stripes (subtle)
  for (let x = 0; x < 512; x += 40) {
    ctx.fillStyle = `${secondaryColor}18`
    ctx.fillRect(x, 0, 20, 512)
  }

  // Number
  ctx.fillStyle = secondaryColor
  ctx.font = 'bold 180px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillText(String(number), 256, 300)

  // Name
  ctx.font = 'bold 36px Arial'
  ctx.fillText(name.toUpperCase(), 256, 420)

  return new THREE.CanvasTexture(canvas)
}

function Jersey({ club, index }: { club: ClubData; index: number }) {
  const meshRef = useRef<THREE.Mesh>(null)
  const jerseyTexture = useMemo(
    () => createJerseyTexture(club.primaryColor, club.secondaryColor, club.jerseyNumber, club.shortName),
    [club]
  )

  useFrame((state) => {
    if (!meshRef.current) return
    meshRef.current.position.y = Math.sin(state.clock.elapsedTime * 0.8 + index) * 0.08
    meshRef.current.rotation.y = Math.sin(state.clock.elapsedTime * 0.3 + index * 1.5) * 0.08
  })

  return (
    <mesh ref={meshRef} position={[0, 0.5, 0]} castShadow>
      <planeGeometry args={[2.2, 2.6, 1, 1]} />
      <meshStandardMaterial
        map={jerseyTexture}
        side={THREE.DoubleSide}
        roughness={0.7}
        metalness={0.1}
      />
    </mesh>
  )
}

function Trophy({ position }: { position: [number, number, number] }) {
  const groupRef = useRef<THREE.Group>(null)

  useFrame((state) => {
    if (!groupRef.current) return
    groupRef.current.rotation.y = state.clock.elapsedTime * 0.5
  })

  return (
    <group ref={groupRef} position={position}>
      {/* Base */}
      <mesh position={[0, 0.1, 0]}>
        <cylinderGeometry args={[0.15, 0.2, 0.1, 8]} />
        <meshStandardMaterial color="#FFD700" metalness={0.9} roughness={0.1} />
      </mesh>
      {/* Stem */}
      <mesh position={[0, 0.35, 0]}>
        <cylinderGeometry args={[0.04, 0.06, 0.4, 8]} />
        <meshStandardMaterial color="#FFD700" metalness={0.9} roughness={0.1} />
      </mesh>
      {/* Cup */}
      <mesh position={[0, 0.65, 0]}>
        <cylinderGeometry args={[0.18, 0.08, 0.35, 12, 1, true]} />
        <meshStandardMaterial color="#FFD700" metalness={0.9} roughness={0.1} side={THREE.DoubleSide} />
      </mesh>
      <pointLight color="#FFD700" intensity={0.5} distance={1.5} position={[0, 0.8, 0]} />
    </group>
  )
}

interface Props {
  activeClub: string
  clubs: ClubData[]
}

export function ClubScene({ activeClub, clubs }: Props) {
  const club = clubs.find((c) => c.id === activeClub) ?? clubs[0]
  const trophyCount = Math.min(club.trophies.length, 4)

  return (
    <>
      <color attach="background" args={['#030313']} />
      <fog attach="fog" args={['#030313', 8, 20]} />
      <ambientLight intensity={0.05} />

      {/* Main spotlight on jersey */}
      <spotLight
        position={[0, 5, 3]}
        angle={0.3}
        penumbra={0.8}
        intensity={3}
        color={club.primaryColor}
        castShadow
        shadow-mapSize={[1024, 1024]}
      />
      <spotLight
        position={[-3, 4, 1]}
        angle={0.4}
        penumbra={1}
        intensity={1.5}
        color={club.accentColor}
      />

      <Environment preset="studio" />

      {/* Jersey */}
      <Jersey club={club} index={0} />

      {/* Glow plane behind jersey */}
      <mesh position={[0, 0.5, -0.5]} rotation={[0, 0, 0]}>
        <planeGeometry args={[4, 4]} />
        <meshBasicMaterial
          color={club.primaryColor}
          transparent
          opacity={0.06}
          blending={THREE.AdditiveBlending}
        />
      </mesh>

      {/* Floor */}
      <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -1.2, 0]} receiveShadow>
        <planeGeometry args={[20, 20]} />
        <MeshReflectorMaterial
          blur={[300, 100]}
          resolution={512}
          mixBlur={1}
          mixStrength={40}
          roughness={1}
          depthScale={1.2}
          minDepthThreshold={0.4}
          maxDepthThreshold={1.4}
          color="#050520"
          metalness={0.6}
          mirror={0}
        />
      </mesh>

      {/* Trophy shelf */}
      {trophyCount > 0 && (
        <group position={[0, -0.8, -1.5]}>
          {/* Shelf */}
          <mesh position={[0, 0, 0]}>
            <boxGeometry args={[(trophyCount - 1) * 0.8 + 0.6, 0.04, 0.3]} />
            <meshStandardMaterial color="#1a1a2e" metalness={0.5} roughness={0.5} />
          </mesh>
          {/* Trophies on shelf */}
          {Array.from({ length: trophyCount }).map((_, i) => (
            <Trophy
              key={i}
              position={[
                (i - (trophyCount - 1) / 2) * 0.8,
                0.02,
                0,
              ]}
            />
          ))}
        </group>
      )}
    </>
  )
}
