import { useState, useRef, useEffect, useCallback } from 'react'
import { gsap } from 'gsap'
import { Volume2, VolumeX, AlertTriangle, Loader2 } from 'lucide-react'
import { useReducedMotion } from '../hooks/useReducedMotion'

interface LoadingScreenProps {
  onLoadComplete: () => void
}

export default function LoadingScreen({ onLoadComplete }: LoadingScreenProps) {
  const [accepted, setAccepted] = useState(false)
  const [loading, setLoading] = useState(false)
  const [progress, setProgress] = useState(0)
  const [audioEnabled, setAudioEnabled] = useState(true)
  const [exiting, setExiting] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)
  const audioRef = useRef<HTMLAudioElement | null>(null)
  const reducedMotion = useReducedMotion()

  useEffect(() => {
    audioRef.current = new Audio('./media/moan.mp3')
    audioRef.current.preload = 'auto'
  }, [])

  useEffect(() => {
    if (!containerRef.current || reducedMotion) return
    gsap.fromTo(
      containerRef.current.querySelectorAll('.load-item'),
      { y: 30, opacity: 0 },
      { y: 0, opacity: 1, duration: 0.8, stagger: 0.12, ease: 'expo.out', delay: 0.2 }
    )
  }, [reducedMotion])

  const handleLoad = useCallback(() => {
    if (!accepted || loading) return
    setLoading(true)

    // Play moan audio during loading
    if (audioEnabled && audioRef.current) {
      audioRef.current.volume = 0.6
      audioRef.current.play().catch(() => {
        // Audio blocked by browser policy, continue anyway
      })
    }

    // Simulate loading progress
    const startTime = Date.now()
    const duration = 2500 // 2.5s minimum load time

    const updateProgress = () => {
      const elapsed = Date.now() - startTime
      const p = Math.min((elapsed / duration) * 100, 100)
      setProgress(p)

      if (p < 100) {
        requestAnimationFrame(updateProgress)
      } else {
        // Finish loading
        setTimeout(() => {
          // Stop moan.mp3 before transitioning
          if (audioRef.current) {
            audioRef.current.pause()
            audioRef.current.currentTime = 0
          }
          setExiting(true)
          setTimeout(() => {
            onLoadComplete()
          }, 800)
        }, 300)
      }
    }
    requestAnimationFrame(updateProgress)
  }, [accepted, loading, audioEnabled, onLoadComplete])

  return (
    <div
      ref={containerRef}
      className={`fixed inset-0 z-[100] flex flex-col items-center justify-center bg-grey-900 transition-all duration-700 ${
        exiting ? 'opacity-0 scale-105' : 'opacity-100 scale-100'
      }`}
      style={{ pointerEvents: exiting ? 'none' : 'auto' }}
    >
      {/* Ambient background shapes */}
      {!reducedMotion && (
        <>
          <div className="absolute top-1/4 left-1/4 w-64 h-64 rounded-full bg-pink-brand/5 blur-3xl ambient-shape-1" />
          <div className="absolute bottom-1/3 right-1/4 w-96 h-96 rounded-full bg-pink-soft/5 blur-3xl ambient-shape-2" />
        </>
      )}

      <div className="relative z-10 flex flex-col items-center max-w-md w-full px-6">
        {/* Banner image */}
        <div className="load-item mb-8 relative">
          <div className="overflow-hidden rounded-lg shadow-2xl shadow-pink-brand/10">
            <img
              src="./media/bg.png"
              alt="Banner"
              className="w-48 h-auto object-cover"
              draggable={false}
            />
          </div>
          {!reducedMotion && (
            <div className="absolute -inset-1 rounded-lg bg-pink-brand/20 blur-xl -z-10 animate-pulse-slow" />
          )}
        </div>

        {/* Load text */}
        <h1 className="load-item text-4xl md:text-5xl font-mono font-light text-skin-100 tracking-widest mb-2">
          Load~
        </h1>

        <p className="load-item text-grey-500 text-sm mb-8 font-body">
          depoliticized.
        </p>

        {/* Warning */}
        <div className="load-item w-full mb-6">
          <div className="flex items-start gap-3 p-4 rounded-xl bg-yellow-500/10 border border-yellow-500/20">
            <AlertTriangle className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
            <div className="flex-1">
              <label className="flex items-start gap-3 cursor-pointer group">
                <input
                  type="checkbox"
                  checked={accepted}
                  onChange={(e) => setAccepted(e.target.checked)}
                  className="mt-1 w-4 h-4 rounded border-yellow-500/30 bg-transparent accent-pink-brand focus:ring-pink-brand/50 focus:ring-2"
                />
                <span className="text-yellow-200/80 text-xs leading-relaxed font-body">
                  I acknowledge that the creator is not responsible for any content shown on this page. All links, features, contacts, projects, etc. are entirely for research and personal educational purposes, not meant to be deployed or actually harm anyone.
                </span>
              </label>
            </div>
          </div>
        </div>

        {/* Audio toggle */}
        <div className="load-item flex items-center gap-2 mb-6">
          <button
            onClick={() => setAudioEnabled(!audioEnabled)}
            className="flex items-center gap-2 text-xs text-grey-500 hover:text-pink-soft transition-colors"
          >
            {audioEnabled ? <Volume2 className="w-4 h-4" /> : <VolumeX className="w-4 h-4" />}
            <span>{audioEnabled ? 'Sound on' : 'Sound off'}</span>
          </button>
        </div>

        {/* Load button */}
        <button
          onClick={handleLoad}
          disabled={!accepted || loading}
          className={`load-item group relative px-12 py-4 rounded-full font-display font-medium text-sm tracking-wider uppercase transition-all duration-300 overflow-hidden ${
            accepted && !loading
              ? 'bg-pink-brand text-white hover:bg-pink-bright hover:shadow-lg hover:shadow-pink-brand/30 hover:scale-105'
              : 'bg-grey-700 text-grey-500 cursor-not-allowed'
          }`}
        >
          {loading ? (
            <span className="flex items-center gap-2">
              <Loader2 className="w-4 h-4 animate-spin" />
              Loading...
            </span>
          ) : (
            <span className="relative z-10">Load</span>
          )}
          {!loading && accepted && !reducedMotion && (
            <span className="absolute inset-0 bg-pink-bright translate-y-full group-hover:translate-y-0 transition-transform duration-300 ease-out" />
          )}
        </button>

        {/* Progress bar */}
        {loading && (
          <div className="load-item w-full mt-8">
            <div className="h-1 w-full bg-grey-700 rounded-full overflow-hidden">
              <div
                className="h-full bg-pink-brand rounded-full transition-all duration-100 ease-out"
                style={{ width: `${progress}%` }}
              />
            </div>
            <p className="text-center text-grey-500 text-xs mt-2 font-mono">
              {Math.round(progress)}%
            </p>
          </div>
        )}
      </div>
    </div>
  )
}
