'use client';

import React, { useState, useEffect } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { 
  Search, 
  Globe, 
  Users, 
  BookOpen, 
  Award, 
  MapPin, 
  Calendar, 
  ArrowRight,
  Shield,
  Sparkles,
  MessageSquare,
  Phone,
  Mail,
  User
} from 'lucide-react';

// Import Shared Components
import ModernCard from '../../components/shared/ModernCard';
import StatCard from '../../components/shared/StatCard';

const ITEMS_PER_PAGE = 6;

// Helper function to get S3 URL
const getS3Url = (imagePath) => {
  if (!imagePath) return null;
  
  if (imagePath.startsWith('/')) {
    return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${imagePath.replace(/^\/+/, "")}`;
  }
  
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  
  return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${imagePath}`;
};

const CountriesGuide = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const [guides, setGuides] = useState([]);
    const [guidesLoading, setGuidesLoading] = useState(true);
    const [totalItems, setTotalItems] = useState(0);
    const [totalPages, setTotalPages] = useState(1);
    const [searchTerm, setSearchTerm] = useState('');
    const [filteredGuides, setFilteredGuides] = useState([]);

    // Fetch guides from API
    useEffect(() => {
        const fetchGuides = async () => {
            try {
                setGuidesLoading(true);
                const response = await fetch(`/api/frontend/getguides?page=${currentPage}&limit=${ITEMS_PER_PAGE}`);
                if (!response.ok) throw new Error('Failed to fetch guides');
                const data = await response.json();
                const fetchedGuides = Array.isArray(data.data) ? data.data : [];
                setGuides(fetchedGuides);
                setTotalItems(data.meta?.totalItems || (Array.isArray(data.data) ? data.data.length : 0));
                setTotalPages(data.meta?.totalPages || 1);
            } catch (error) {
                console.error('Error fetching guides:', error);
                setGuides([]);
                setTotalItems(0);
                setTotalPages(1);
            } finally {
                setGuidesLoading(false);
            }
        };

        fetchGuides();
    }, [currentPage]);

    // Filter guides based on search term
    useEffect(() => {
        let filtered = [];
        if (searchTerm.trim() === '') {
            filtered = guides;
        } else {
            filtered = guides.filter(guide =>
                guide.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                guide.description?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                guide.country?.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }
        setFilteredGuides(filtered);
    }, [searchTerm, guides]);

    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    const endIndex = startIndex + filteredGuides.length;
    const currentData = filteredGuides;

    const handlePageChange = (page) => {
        if (page >= 1 && page <= totalPages) {
            setCurrentPage(page);
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    };

    // Stats data - Updated to match FreeConsultation style
    const stats = [
        { Icon: Globe, number: '50+', label: 'Countries Covered', color: 'teal' },
        { Icon: Users, number: '10K+', label: 'Students Guided', color: 'blue' },
        { Icon: BookOpen, number: '1500+', label: 'Universities', color: 'emerald' },
        { Icon: Award, number: '99%', label: 'Success Rate', color: 'amber' }
    ];

    return (
        <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
            {/* Hero Section - Matching FreeConsultation design */}
            <div className="relative">
                <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
                
                <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
                    {[...Array(20)].map((_, i) => (
                        <div
                            key={i}
                            className="absolute rounded-full bg-linear-to-r from-teal-200/20 to-blue-200/20 animate-float"
                            style={{
                                width: Math.random() * 100 + 50,
                                height: Math.random() * 100 + 50,
                                top: `${Math.random() * 100}%`,
                                left: `${Math.random() * 100}%`,
                                animationDelay: `${Math.random() * 5}s`,
                                animationDuration: `${Math.random() * 10 + 10}s`
                            }}
                        />
                    ))}
                </div>

                <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 md:py-28">
                    <div className="text-center">
                        <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-8 animate-pulse">
                            <Globe className="w-5 h-5" />
                            Global Study Guides
                        </div>

                        <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
                            Your{' '}
                            <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                                Study Abroad
                            </span>{' '}
                            <br />
                            Journey Starts Here
                        </h1>

                        <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
                            Access comprehensive guides to top universities, application timelines, and visa requirements for over 50 countries.
                        </p>

                        {/* Search Bar - Matching design */}
                        <div className="max-w-2xl mx-auto mt-8">
                            <div className="relative">
                                <Search className="absolute left-5 top-1/2 transform -translate-y-1/2 text-gray-400 z-10" />
                                <input
                                    type="text"
                                    placeholder="Search for a country or university guide..."
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="w-full pl-14 pr-6 py-4 rounded-xl border border-gray-300 bg-white/80 backdrop-blur-sm shadow-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500 text-gray-700 transition-all duration-300"
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Stats Section - Matching FreeConsultation design */}
            <div className="py-16">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="text-center mb-12">
                        <h2 className="text-3xl font-bold text-gray-900 mb-4">
                            Why Students Trust Our Guides
                        </h2>
                        <p className="text-gray-600 max-w-2xl mx-auto">
                            Comprehensive resources to help you make informed decisions about studying abroad
                        </p>
                    </div>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
                        {stats.map((stat, index) => (
                            <StatCard 
                                key={index}
                                Icon={stat.Icon}
                                number={stat.number}
                                label={stat.label}
                                color={stat.color}
                            />
                        ))}
                    </div>
                </div>
            </div>

            {/* Guides Section */}
            <div className="py-20">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="text-center mb-12">
                        <h2 className="text-3xl font-bold text-gray-900 mb-4">
                            Explore{' '}
                            <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                                Country Guides
                            </span>
                        </h2>
                        <p className="text-gray-600 mt-4 max-w-2xl mx-auto text-lg">
                            {searchTerm ? `Showing results for "${searchTerm}"` : 'Browse all available country guides for a seamless study abroad experience.'}
                        </p>
                    </div>

                    {/* Guide List */}
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                        {guidesLoading ? (
                            Array.from({ length: 6 }).map((_, idx) => (
                                <ModernCard key={idx} className="animate-pulse overflow-hidden">
                                    <div className="relative w-full h-56 bg-linear-to-br from-gray-200 to-gray-300"></div>
                                    <div className="p-6">
                                        <div className="h-6 bg-gray-300 rounded w-3/4 mb-4"></div>
                                        <div className="h-4 bg-gray-300 rounded w-full mb-2"></div>
                                        <div className="h-4 bg-gray-300 rounded w-5/6"></div>
                                    </div>
                                </ModernCard>
                            ))
                        ) : currentData.length > 0 ? (
                            currentData.map((guide, idx) => {
                                const guideImageUrl = getS3Url(guide.image);
                                const authorImageUrl = guide.author_image ? getS3Url(guide.author_image) : null;
                                
                                return (
                                    <div key={guide.id} className="group h-full">
                                        <ModernCard className="overflow-hidden hover:shadow-xl transition-all duration-300 cursor-pointer h-full flex flex-col">
                                            {/* Guide Image with Link */}
                                            <Link href={`/guides/${guide.slug}`} className="block">
                                                <div className="relative h-56 overflow-hidden">
                                                    {guideImageUrl ? (
                                                        <Image
                                                            src={guideImageUrl}
                                                            alt={guide.title || "Country Guide"}
                                                            fill
                                                            className="object-cover transition-transform duration-500 group-hover:scale-110"
                                                            unoptimized={guideImageUrl.includes('s3.amazonaws.com')}
                                                        />
                                                    ) : (
                                                        <div className="w-full h-full bg-linear-to-br from-teal-100 to-blue-100 flex items-center justify-center">
                                                            <Globe className="w-12 h-12 text-teal-300" />
                                                        </div>
                                                    )}
                                                    <div className="absolute inset-0 bg-linear-to-t from-black/60 via-transparent to-transparent"></div>
                                                    <div className="absolute top-4 left-4">
                                                        <div className="bg-linear-to-r from-teal-600 to-blue-500 text-white font-bold text-sm px-3 py-1 rounded-full">
                                                            {(startIndex + idx + 1).toString().padStart(2, '0')}
                                                        </div>
                                                    </div>
                                                </div>
                                            </Link>
                                            
                                            <div className="p-6 grow flex flex-col">
                                                {/* Guide Title with Link */}
                                                <Link href={`/guides/${guide.slug}`} className="block mb-3">
                                                    <div className="flex justify-between items-start">
                                                        <h3 className="text-xl font-bold text-gray-900 leading-tight line-clamp-2 hover:text-teal-600 transition-colors">
                                                            {guide.title}
                                                        </h3>
                                                        <ArrowRight className="w-5 h-5 text-gray-400 transition-transform group-hover:translate-x-2 shrink-0 mt-1" />
                                                    </div>
                                                </Link>
                                                
                                                {guide.description && (
                                                    <div 
                                                        className="text-gray-600 text-sm mt-2 line-clamp-3 grow"
                                                        dangerouslySetInnerHTML={{ __html: guide.description }}
                                                    />
                                                )}
                                                
                                                {/* Author and Date - Author is now clickable */}
                                                <div className="mt-4 pt-4 border-t border-gray-100 flex justify-between items-center text-xs text-gray-500">
                                                    <div className="flex items-center gap-2">
                                                        {/* Author Image */}
                                                        {authorImageUrl ? (
                                                            <Link 
                                                                href={`/author/${guide.author_slug || 'admin'}`}
                                                                onClick={(e) => e.stopPropagation()}
                                                                className="relative w-6 h-6 rounded-full overflow-hidden shrink-0"
                                                            >
                                                                <Image
                                                                    src={authorImageUrl}
                                                                    alt={guide.author_name || 'Author'}
                                                                    fill
                                                                    sizes="24px"
                                                                    className="object-cover"
                                                                    unoptimized={authorImageUrl.includes('s3.amazonaws.com')}
                                                                />
                                                            </Link>
                                                        ) : guide.author_name ? (
                                                            <div className="w-6 h-6 rounded-full bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center shrink-0">
                                                                <User className="w-3 h-3 text-teal-500" />
                                                            </div>
                                                        ) : null}
                                                        
                                                        {/* Author Name Link */}
                                                        {guide.author_name ? (
                                                            <Link 
                                                                href={`/author/${guide.author_slug || 'admin'}`}
                                                                onClick={(e) => e.stopPropagation()}
                                                                className="flex items-center gap-1 text-gray-600 hover:text-teal-600 transition-colors font-medium"
                                                            >
                                                                <span>{guide.author_name}</span>
                                                            </Link>
                                                        ): <Link 
                                                                href={`/author/${guide.author_slug || 'admin'}`}
                                                                onClick={(e) => e.stopPropagation()}
                                                                className="flex items-center gap-1 text-gray-600 hover:text-teal-600 transition-colors font-medium"
                                                            >
                                                                <span>{guide.author_name || 'Admin'}</span>
                                                            </Link>}
                                                    </div>
                                                    
                                                    <span className="flex items-center gap-1">
                                                        <Calendar className="w-3 h-3" />
                                                        {guide.updated_at ? new Date(guide.updated_at).toLocaleDateString() : 'Recently updated'}
                                                    </span>
                                                </div>
                                            </div>
                                        </ModernCard>
                                    </div>
                                );
                            })
                        ) : (
                            <div className="col-span-full text-center py-16">
                                <div className="text-6xl mb-4">🔍</div>
                                <div className="text-2xl font-bold mb-2 bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                                    No guides found
                                </div>
                                <p className="text-gray-500 max-w-md mx-auto">
                                    {searchTerm ? `No guides match your search for "${searchTerm}". Try different keywords.` : 'No guides are available yet. Check back soon!'}
                                </p>
                            </div>
                        )}
                    </div>

                    {/* Pagination */}
                    {totalPages > 1 && currentData.length > 0 && (
                        <div className="mt-12 flex justify-center">
                            <div className="flex items-center gap-2">
                                <button
                                    onClick={() => handlePageChange(currentPage - 1)}
                                    disabled={currentPage === 1}
                                    className="px-4 py-2 rounded-lg border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
                                >
                                    Previous
                                </button>
                                
                                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                                    let pageNum;
                                    if (totalPages <= 5) {
                                        pageNum = i + 1;
                                    } else if (currentPage <= 3) {
                                        pageNum = i + 1;
                                    } else if (currentPage >= totalPages - 2) {
                                        pageNum = totalPages - 4 + i;
                                    } else {
                                        pageNum = currentPage - 2 + i;
                                    }
                                    
                                    return (
                                        <button
                                            key={pageNum}
                                            onClick={() => handlePageChange(pageNum)}
                                            className={`px-4 py-2 rounded-lg transition-colors ${
                                                currentPage === pageNum
                                                    ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white'
                                                    : 'border border-gray-300 hover:bg-gray-50'
                                            }`}
                                        >
                                            {pageNum}
                                        </button>
                                    );
                                })}
                                
                                <button
                                    onClick={() => handlePageChange(currentPage + 1)}
                                    disabled={currentPage === totalPages}
                                    className="px-4 py-2 rounded-lg border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
                                >
                                    Next
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {/* CTA Section - Matching FreeConsultation design */}
            <div className="py-20">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-8 md:p-12 text-center">
                        <h2 className="text-3xl md:text-4xl font-bold text-white mb-4">
                            Ready to Begin Your Adventure?
                        </h2>
                        <p className="text-white/80 text-lg mb-8 max-w-2xl mx-auto">
                            Our team of experts is ready to provide personalized guidance and support to make your dreams a reality.
                        </p>
                        <div className="flex flex-col sm:flex-row gap-4 justify-center">
                            <Link href="/contact" passHref>
                                <button className="inline-flex items-center justify-center gap-2 bg-white text-teal-700 font-semibold py-3 px-8 rounded-xl hover:bg-gray-100 transition-all duration-300 transform hover:scale-105">
                                    <MessageSquare className="w-4 h-4" />
                                    Book a Free Consultation
                                </button>
                            </Link>
                            <Link href="/resources" passHref>
                                <button className="inline-flex items-center justify-center gap-2 border-2 border-white/30 text-white font-semibold py-3 px-8 rounded-xl hover:bg-white/10 transition-all duration-300 transform hover:scale-105">
                                    <BookOpen className="w-4 h-4" />
                                    Download Application Checklist
                                </button>
                            </Link>
                        </div>
                        
                        {/* Contact Info - Matching FreeConsultation */}
                        <div className="mt-12 pt-8 border-t border-white/20">
                            <p className="text-white/80 mb-6">Contact us directly for immediate assistance</p>
                            <div className="flex flex-col sm:flex-row gap-4 justify-center">
                                <a 
                                    href="tel:+923330033235" 
                                    className="inline-flex items-center justify-center gap-2 bg-white/20 backdrop-blur-sm text-white font-semibold py-3 px-6 rounded-xl hover:bg-white/30 transition-all duration-300"
                                >
                                    <Phone className="w-4 h-4" />
                                    Call Now
                                </a>
                                <a 
                                    href="mailto:info@universitiespage.com" 
                                    className="inline-flex items-center justify-center gap-2 border-2 border-white/30 text-white font-semibold py-3 px-6 rounded-xl hover:bg-white/10 transition-all duration-300"
                                >
                                    <Mail className="w-4 h-4" />
                                    Email Us
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default CountriesGuide;