'use client';

import React, { useState, useEffect } from 'react';
import Image from 'next/image';

interface HeroImage {
  id: number;
  title: string;
  subtitle: string;
  description: string;
  imageUrl: string;
  imageFilename: string;
  isActive: boolean;
  uploadDate: string;
  lastModified: string;
}

const HeroSection = () => {
  const [heroData, setHeroData] = useState<HeroImage | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  // Default fallback data
  const defaultHeroData = {
    title: 'This year, we celebrate',
    subtitle: '125 years of CMC Vellore',
    description: '1900 - 2025',
    imageUrl: '/images/hero.png',
  };

  useEffect(() => {
    const fetchHeroImage = async () => {
      try {
        const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
        console.log('Fetching from:', `${apiUrl}/hero/active`); // Debug log
        
        const response = await fetch(`${apiUrl}/hero/active`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
          cache: 'no-store', // Disable caching to always get fresh data
        });
        
        if (response.ok) {
          const data: HeroImage = await response.json();
          console.log('Hero image data:', data); // Debug log
          setHeroData(data);
          setError(false);
        } else {
          console.error('Failed to fetch hero image:', response.status);
          setError(true);
        }
      } catch (err) {
        console.error('Error fetching hero image:', err);
        setError(true);
      } finally {
        setLoading(false);
      }
    };

    fetchHeroImage();
  }, []);

  // Use fetched data or fall back to default
  const displayData = heroData || defaultHeroData;
  
  // ✅ FIX: Construct full image URL with API base URL
  const getImageUrl = () => {
    if (!heroData) {
      return defaultHeroData.imageUrl; // Local fallback image
    }
    
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
    
    // If imageUrl already contains the full URL (starts with http), use it directly
    if (heroData.imageUrl.startsWith('http')) {
      return heroData.imageUrl;
    }
    
    // Otherwise, construct the full URL
    // Remove leading slash from imageUrl if present to avoid double slashes
    const imagePath = heroData.imageUrl.startsWith('/') 
      ? heroData.imageUrl.slice(1) 
      : heroData.imageUrl;
    
    return `${apiUrl}/${imagePath}`;
  };

  const imageUrl = getImageUrl();
  
  console.log('Final image URL:', imageUrl); // Debug log

  return (
    <div className="relative h-80 md:h-96 lg:h-[380px] min-h-80 md:min-h-96 lg:min-h-[500px] overflow-hidden">
      {/* Background Image */}
      {heroData ? (
        // For API images - use full URL with API base
        <img 
          src={imageUrl}
          alt={displayData.title}
          className="absolute inset-0 w-full h-full object-cover"
          onError={(e) => {
            console.error('Image failed to load:', imageUrl);
            // Fallback to default image on error
            e.currentTarget.src = defaultHeroData.imageUrl;
          }}
        />
      ) : (
        // For local images (fallback)
        <Image 
          src={imageUrl}
          alt={displayData.title}
          fill
          className="object-cover"
          priority
        />
      )}
      
      {/* Main Content */}
      <div className="relative z-10 flex items-center h-full px-4 sm:px-6 md:px-8 lg:px-12 xl:px-16 2xl:px-24">
        <div className="max-w-2xl lg:max-w-3xl">
          {/* Glass Card */}
          <div className="bg-black/10 backdrop-blur-[1px] rounded-2xl p-8 sm:p-10 md:p-12 lg:p-4 shadow-2xl border border-white/30">
            {/* Main Heading */}
            <h1 className="mb-6 sm:mb-8 md:mb-10" style={{ color: '#fff' }}>
                  <div className="text-lg sm:text-xl md:text-2xl lg:text-3xl xl:text-4xl 2xl:text-5xl font-semibold leading-tight mb-1 sm:mb-2 md:mb-3 lg:mb-4">
                    This year, we celebrate <span className='text-5xl text-bold'>125 years</span>
                  </div>
                  <div className="text-lg sm:text-xl md:text-2xl lg:text-3xl xl:text-4xl 2xl:text-5xl font-semibold leading-tight mb-1 sm:mb-2 md:mb-3 lg:mb-4">
                    of CMC Vellore
                  </div>
                  <div className="text-base sm:text-lg md:text-xl lg:text-2xl xl:text-3xl 2xl:text-4xl font-semibold" style={{ color: '#fff' }}>
                    1900 - 2025
                  </div>
            </h1>
            
            {/* CTA Button */}
            <a 
              href="https://www.cmch-vellore.edu/" 
              target="_blank" 
              rel="noopener noreferrer"
            >
              <button 
                className="bg-red-600 hover:bg-red-700 text-white px-6 py-3 sm:px-8 sm:py-4 md:px-10 md:py-4 text-sm sm:text-base md:text-lg font-semibold rounded-lg transition-all duration-300 shadow-lg hover:shadow-xl hover:-translate-y-0.5 focus:outline-none focus:ring-4 focus:ring-red-300"
                style={{ backgroundColor: '#e64838' }}
              >
                Discover
              </button>
            </a>
          </div>
        </div>
      </div>

      {/* Loading indicator */}
      {loading && (
        <div className="absolute top-4 right-4 z-20">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
        </div>
      )}

      {/* Error indicator (for debugging) */}
      {error && process.env.NODE_ENV === 'development' && (
        <div className="absolute top-4 left-4 z-20 bg-red-500 text-white px-4 py-2 rounded">
          Failed to load hero image
        </div>
      )}
    </div>
  );
};

export default HeroSection;