'use client'

import { useEffect, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import Image from 'next/image'

export default function IntroPage() {
  const videoRef = useRef<HTMLVideoElement>(null)
  const router = useRouter()
  const [isLoading, setIsLoading] = useState(true)
  const [videoError, setVideoError] = useState(false)
  const hasAttemptedPlay = useRef(false)

  useEffect(() => {
    const video = videoRef.current
    if (!video) return

    let loadingTimer: NodeJS.Timeout
    let errorTimer: NodeJS.Timeout

    // Function to attempt video playback
    const attemptPlay = async () => {
      if (hasAttemptedPlay.current) return
      hasAttemptedPlay.current = true

      try {
        // Start muted for better autoplay compatibility
        video.muted = true
        await video.play()
        
        // Set playback rate after successful play
        video.playbackRate = 0.6
        
        // Hide loading screen
        setIsLoading(false)
        
        console.log('Video playing successfully')
      } catch (error) {
        console.error('Video play error:', error)
        setVideoError(true)
        // Redirect to home after error
        errorTimer = setTimeout(() => {
          router.push('/home')
        }, 2000)
      }
    }

    // Handle when video can play
    const handleCanPlay = () => {
      console.log('Video can play')
      // Wait minimum 2 seconds for loading screen
      loadingTimer = setTimeout(() => {
        attemptPlay()
      }, 2000)
    }

    // Handle video end event
    const handleVideoEnd = () => {
      console.log('Video ended')
      // Delay 2 seconds before redirecting to home
      setTimeout(() => {
      router.push('/home')
      }, 2000)
    }

    // Handle video error
    const handleError = (e: Event) => {
      console.error('Video load error:', e)
      setVideoError(true)
      errorTimer = setTimeout(() => {
        router.push('/home')
      }, 2000)
    }

    // Add event listeners
    video.addEventListener('canplay', handleCanPlay)
    video.addEventListener('ended', handleVideoEnd)
    video.addEventListener('error', handleError)

    // Start loading the video
    video.load()

    // Fallback: if video doesn't load within 10 seconds, redirect
    const fallbackTimer = setTimeout(() => {
      if (isLoading) {
        console.log('Video took too long, redirecting to home')
        router.push('/home')
      }
    }, 10000)

    // Cleanup
    return () => {
      clearTimeout(loadingTimer)
      clearTimeout(errorTimer)
      clearTimeout(fallbackTimer)
      video.removeEventListener('canplay', handleCanPlay)
      video.removeEventListener('ended', handleVideoEnd)
      video.removeEventListener('error', handleError)
    }
  }, [router])

  return (
    <div className="fixed inset-0 z-[9999] bg-black flex items-center justify-center">
      {isLoading && (
        <div className="absolute inset-0 flex flex-col items-center justify-center bg-black z-50">
          <Image
            src="/Information/Images/Madibeng-logo-petals.gif"
            alt="Loading"
            width={200}
            height={200}
            className="object-contain"
            unoptimized
          />
          <p className="text-white text-lg font-medium mt-4">
            {videoError ? 'Redirecting...' : 'Loading...'}
          </p>
        </div>
      )}
      <video
        ref={videoRef}
        src="/Information/Video/IntroVideo.mp4"
        className={`w-full lg:w-1/2 h-full object-contain transition-opacity duration-500 ${isLoading ? 'opacity-0' : 'opacity-100'}`}
        playsInline
        preload="auto"
        muted
      />
    </div>
  )
}
