"use client"

import { useState, useEffect, useRef } from "react"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { ChevronLeft, ChevronRight, ExternalLink, Megaphone } from "lucide-react"
import { motion, AnimatePresence, useInView } from "framer-motion"
import Link from "next/link"
import { 
  getOrCreateSessionId, 
  hasTrackedImpression, 
  markImpressionTracked,
  getSessionStats 
} from "@/lib/ad-session"

export type AdPlacementType = "top-banner" | "right-side" | "left-side"

export interface AdData {
  id: string
  title: string
  description?: string
  imageUrl: string
  facilityName: string
  location?: string
  category?: string
  placementType: AdPlacementType
  link: string
}

interface AdCarouselProps {
  ads: AdData[]
  placementType: AdPlacementType
  autoPlayInterval?: number
}

export function AdCarousel({ ads, placementType, autoPlayInterval = 5000 }: AdCarouselProps) {
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isAutoPlaying, setIsAutoPlaying] = useState(true)
  const [sessionId, setSessionId] = useState<string>('')
  const carouselRef = useRef(null)
  const isInView = useInView(carouselRef, { once: false, amount: 0.5 })
  const viewTimerRef = useRef<NodeJS.Timeout | null>(null)

  // Initialize session on mount
  useEffect(() => {
    const id = getOrCreateSessionId()
    setSessionId(id)
    
    // Log session stats for debugging
    const stats = getSessionStats()
    console.log('[Ad Carousel] Session initialized:', stats)
  }, [])

  // Helper function to get proper image URL
  const getImageUrl = (imageUrl: string): string => {
    if (!imageUrl) {
      return '/placeholder.svg'
    }
    
    // If it's already an absolute URL (S3, CDN, etc.), return as is
    if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
      return imageUrl
    }
    
    // If it starts with /, it's a relative path from public folder
    if (imageUrl.startsWith('/')) {
      return imageUrl
    }
    
    // If it contains uploads/ or starts with uploads, ensure it has leading slash
    if (imageUrl.includes('uploads/')) {
      return imageUrl.startsWith('/') ? imageUrl : `/${imageUrl}`
    }
    
    // Otherwise, prepend /uploads/ads/ if it's just a filename
    return `/uploads/ads/${imageUrl}`
  }

  // Auto-play carousel
  useEffect(() => {
    if (!isAutoPlaying || ads.length <= 1) return

    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % ads.length)
    }, autoPlayInterval)

    return () => clearInterval(interval)
  }, [isAutoPlaying, ads.length, autoPlayInterval])

  // Helper function to check if ID is a valid MongoDB ObjectId
  const isValidObjectId = (id: string): boolean => {
    return /^[0-9a-fA-F]{24}$/.test(id)
  }

  // Track impressions when ad is viewed (IAB/MRC standards)
  // Requirements: 50% visible in viewport for 1+ continuous second
  useEffect(() => {
    // Clear any existing timer when ad changes or visibility changes
    if (viewTimerRef.current) {
      clearTimeout(viewTimerRef.current)
      viewTimerRef.current = null
    }

    // Validate preconditions
    if (ads.length === 0) return
    if (!isInView) {
      console.log('[Ad Carousel] Ad not in view, skipping impression tracking')
      return
    }

    const currentAd = ads[currentIndex]
    if (!currentAd) return

    // Only track impressions for real ads (valid MongoDB ObjectIds)
    if (!isValidObjectId(currentAd.id)) {
      console.log('[Ad Carousel] Skipping - invalid ObjectId:', currentAd.id)
      return
    }

    // Check if already tracked in this session
    const alreadyTracked = hasTrackedImpression(currentAd.id)
    
    console.log('[Ad Carousel] Impression check:', {
      adId: currentAd.id,
      facilityName: currentAd.facilityName,
      isInView,
      alreadyTracked,
      sessionId
    })

    if (alreadyTracked) {
      console.log('[Ad Carousel] Already tracked impression in this session:', currentAd.id)
      return
    }

    // Track impression after 1 second of continuous visibility
    const trackImpression = async () => {
      // Verify ad is still visible after 1 second
      if (!isInView) {
        console.log('[Ad Carousel] Ad no longer visible after 1s, skipping impression')
        return
      }

      try {
        console.log('[Ad Carousel] Tracking unique impression:', {
          adId: currentAd.id,
          facilityName: currentAd.facilityName,
          sessionId,
          placementType
        })
        
        const response = await fetch('/api/ads/impression', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ adId: currentAd.id })
        })
        
        const result = await response.json()
        console.log('[Ad Carousel] Impression tracked successfully:', result)
        
        // Mark as tracked in session storage
        markImpressionTracked(currentAd.id)
        
        // Log updated session stats
        const stats = getSessionStats()
        console.log('[Ad Carousel] Session stats after tracking:', stats)
      } catch (error) {
        console.error('[Ad Carousel] Error tracking ad impression:', error)
      }
    }

    // Wait 1 second (IAB/MRC standard) before tracking
    viewTimerRef.current = setTimeout(trackImpression, 1000)
    
    return () => {
      if (viewTimerRef.current) {
        clearTimeout(viewTimerRef.current)
        viewTimerRef.current = null
      }
    }
  }, [isInView, currentIndex, ads, sessionId, placementType])

  const handleAdClick = async (adId: string, facilityName: string) => {
    // Only track clicks for real ads (valid MongoDB ObjectIds)
    if (!isValidObjectId(adId)) {
      console.log('[Ad Carousel] Skipping click - invalid ObjectId:', adId)
      return
    }

    try {
      console.log('[Ad Carousel] Tracking click for:', adId, facilityName)
      const response = await fetch('/api/ads/click', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ adId })
      })
      const result = await response.json()
      console.log('[Ad Carousel] Click tracked successfully:', result)
    } catch (error) {
      console.error('[Ad Carousel] Error tracking ad click:', error)
    }
  }

  const goToNext = () => {
    setCurrentIndex((prev) => (prev + 1) % ads.length)
    setIsAutoPlaying(false)
  }

  const goToPrevious = () => {
    setCurrentIndex((prev) => (prev - 1 + ads.length) % ads.length)
    setIsAutoPlaying(false)
  }

  const goToSlide = (index: number) => {
    setCurrentIndex(index)
    setIsAutoPlaying(false)
  }

  // Different layouts based on placement type
  const getLayoutClasses = () => {
    switch (placementType) {
      case "top-banner":
        return "w-full h-[300px] md:h-[400px] lg:h-[450px]"
      case "right-side":
        return "w-full h-[600px]"
      case "left-side":
        return "w-full h-[600px]"
      default:
        return "w-full h-[300px]"
    }
  }

  // Show placeholder when no ads available
  if (ads.length === 0) {
    return (
      <Card className={`overflow-hidden shadow-lg hover:shadow-xl transition-all duration-300 border-2 border-dashed border-gray-300 rounded-2xl ${getLayoutClasses()}`}>
        <CardContent className="p-0 h-full relative w-full m-0 flex items-center justify-center">
          <div className="text-center p-8 space-y-4">
            <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gradient-to-br from-blue-50 to-indigo-50 mb-4">
              <Megaphone className="h-8 w-8 text-blue-600" />
            </div>
            <h3 className="text-lg font-bold text-gray-900">Ad Placement Available</h3>
            <p className="text-sm text-gray-600 max-w-xs mx-auto">
              This premium ad space is available for your senior care facility. Reach thousands of families searching for care.
            </p>
            <Link href="/advertise">
              <Button className="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-semibold mt-4">
                Advertise With Us
                <ExternalLink className="ml-2 h-4 w-4" />
              </Button>
            </Link>
          </div>
        </CardContent>
      </Card>
    )
  }

  const currentAd = ads[currentIndex]

  const getBadgeColor = () => {
    switch (placementType) {
      case "top-banner":
        return "bg-gradient-to-r from-yellow-500 to-orange-500"
      case "right-side":
        return "bg-gradient-to-r from-blue-500 to-purple-500"
      case "left-side":
        return "bg-gradient-to-r from-green-500 to-teal-500"
      default:
        return "bg-gradient-to-r from-gray-500 to-gray-600"
    }
  }

  const getTitle = () => {
    switch (placementType) {
      case "top-banner":
        return "Premium Sponsored Facility"
      case "right-side":
        return "Featured Partner"
      case "left-side":
        return "Sponsored Listing"
      default:
        return "Sponsored"
    }
  }

  return (
    <div ref={carouselRef} className="relative group w-full">
      <Card className={`overflow-hidden shadow-xl hover:shadow-2xl transition-all duration-300 border-2 border-gray-200/50 rounded-2xl p-0 gap-0 ${getLayoutClasses()}`}>
        <CardContent className="p-0 h-full relative w-full m-0">
          <AnimatePresence mode="wait">
            <motion.div
              key={currentIndex}
              initial={{ opacity: 0, x: 100 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -100 }}
              transition={{ duration: 0.5 }}
              className="h-full w-full"
            >
              <div 
                className="relative h-full w-full cursor-pointer"
                onClick={() => {
                  handleAdClick(currentAd.id, currentAd.facilityName)
                  window.open(currentAd.link, '_blank', 'noopener,noreferrer')
                }}
              >
                {/* Image - Full visible */}
                <div className="absolute inset-0 w-full h-full">
                  <img
                    src={getImageUrl(currentAd.imageUrl)}
                    alt={currentAd.title}
                    className="object-cover w-full h-full"
                    style={{ width: '100%', height: '100%' }}
                    loading="lazy"
                    onError={(e) => {
                      // Fallback to a default placeholder if image fails to load
                      const target = e.target as HTMLImageElement
                      // Try to use a gradient placeholder instead of broken image
                      target.style.display = 'none'
                      const parent = target.parentElement
                      if (parent) {
                        parent.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
                        parent.style.display = 'flex'
                        parent.style.alignItems = 'center'
                        parent.style.justifyContent = 'center'
                        if (!parent.querySelector('.image-error-placeholder')) {
                          const placeholder = document.createElement('div')
                          placeholder.className = 'image-error-placeholder'
                          placeholder.innerHTML = `
                            <div style="text-align: center; color: white; padding: 20px;">
                              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin: 0 auto 10px;">
                                <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
                                <circle cx="8.5" cy="8.5" r="1.5"/>
                                <polyline points="21 15 16 10 5 21"/>
                              </svg>
                              <p style="font-size: 14px; margin: 0;">Image unavailable</p>
                            </div>
                          `
                          parent.appendChild(placeholder)
                        }
                      }
                    }}
                  />
                  {/* Subtle gradient overlay only at bottom for text */}
                  <div className="absolute inset-0 bg-gradient-to-t from-black/75 via-transparent to-transparent" />
                </div>

                {/* Top Badge */}
                <div className="absolute top-3 left-3 z-10">
                  <div className="relative">
                    <div className="absolute inset-0 bg-black/40 blur-sm rounded-full"></div>
                    <span className={`relative ${getBadgeColor()} text-white text-xs font-bold px-3 py-1 rounded-full shadow-lg backdrop-blur-sm`}>
                      {getTitle()}
                    </span>
                  </div>
                </div>

                {/* Bottom Content - Compact */}
                <div className="absolute bottom-0 left-0 right-0 p-4 md:p-5">
                  {/* Compact backdrop for text area only */}
                  <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/60 to-transparent rounded-t-lg"></div>
                  
                  <div className="relative">
                    {/* Title */}
                    <h3 className={`text-white font-bold mb-2 line-clamp-1 ${
                      placementType === 'top-banner' 
                        ? 'text-xl md:text-2xl lg:text-3xl' 
                        : 'text-lg md:text-xl'
                    }`} style={{
                      textShadow: '0 2px 8px rgba(0,0,0,0.9), 0 0 4px rgba(0,0,0,0.8)'
                    }}>
                      {currentAd.facilityName}
                    </h3>
                    
                    {/* Description - Single line (only if provided) */}
                    {currentAd.description && (
                      <p className={`text-white/95 mb-3 line-clamp-1 ${
                        placementType === 'top-banner' 
                          ? 'text-sm md:text-base' 
                          : 'text-xs md:text-sm'
                      }`} style={{
                        textShadow: '0 1px 4px rgba(0,0,0,0.8)'
                      }}>
                        {currentAd.description}
                      </p>
                    )}
                    
                    {/* Badge-style info row (only if location or category provided) */}
                    {(currentAd.location || currentAd.category) && (
                      <div className="flex flex-wrap items-center gap-2 mb-3">
                        {currentAd.location && (
                          <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-black/60 backdrop-blur-sm text-white text-xs font-medium rounded-full border border-white/20" style={{
                            textShadow: '0 1px 2px rgba(0,0,0,0.8)'
                          }}>
                            <span>📍</span>
                            {currentAd.location}
                          </span>
                        )}
                        {currentAd.category && (
                          <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-black/60 backdrop-blur-sm text-white text-xs font-medium rounded-full border border-white/20" style={{
                            textShadow: '0 1px 2px rgba(0,0,0,0.8)'
                          }}>
                            <span>🏥</span>
                            {currentAd.category}
                          </span>
                        )}
                      </div>
                    )}
                    
                    {/* Small Learn More Button */}
                    <Button 
                      variant="secondary" 
                      className="bg-white text-[#3F5CEA] hover:bg-gray-50 font-semibold shadow-lg hover:shadow-xl transition-all text-xs md:text-sm px-4 py-1.5 h-auto"
                      size="sm"
                      onClick={(e) => {
                        e.stopPropagation()
                        handleAdClick(currentAd.id, currentAd.facilityName || '')
                        window.open(currentAd.link, '_blank', 'noopener,noreferrer')
                      }}
                    >
                      Learn More
                      <ExternalLink className="ml-1.5 h-3 w-3" />
                    </Button>
                  </div>
                </div>
              </div>
            </motion.div>
          </AnimatePresence>

          {/* Navigation Arrows */}
          {ads.length > 1 && (
            <>
              <Button
                variant="ghost"
                size="icon"
                className="absolute left-2 top-1/2 -translate-y-1/2 bg-white/90 hover:bg-white shadow-lg opacity-0 group-hover:opacity-100 transition-opacity z-20"
                onClick={(e) => {
                  e.preventDefault()
                  e.stopPropagation()
                  goToPrevious()
                }}
              >
                <ChevronLeft className="h-6 w-6 text-gray-800" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="absolute right-2 top-1/2 -translate-y-1/2 bg-white/90 hover:bg-white shadow-lg opacity-0 group-hover:opacity-100 transition-opacity z-20"
                onClick={(e) => {
                  e.preventDefault()
                  e.stopPropagation()
                  goToNext()
                }}
              >
                <ChevronRight className="h-6 w-6 text-gray-800" />
              </Button>
            </>
          )}

          {/* Dot Indicators */}
          {ads.length > 1 && (
            <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 z-20">
              {ads.map((_, index) => (
                <button
                  key={index}
                  onClick={(e) => {
                    e.preventDefault()
                    e.stopPropagation()
                    goToSlide(index)
                  }}
                  className={`w-2 h-2 rounded-full transition-all duration-300 ${
                    index === currentIndex
                      ? "bg-white w-6"
                      : "bg-white/50 hover:bg-white/75"
                  }`}
                  aria-label={`Go to slide ${index + 1}`}
                />
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Ad Count */}
      {ads.length > 1 && (
        <div className="text-center mt-2 text-sm text-gray-500">
          {currentIndex + 1} / {ads.length}
        </div>
      )}
    </div>
  )
}

