// src/app/main/guides/[slug]/page.jsx

import Image from 'next/image';
import Link from 'next/link';
import { 
  Clock, 
  BookOpen, 
  Calendar,
  Globe,
  Sparkles,
  ChevronRight,
  Home,
  FileText,
  User
} from 'lucide-react';
import TextDisplay from '../../../components/clientcomponents/TextDisplay';
import ModernCard from '../../../components/shared/ModernCard';
import AuthorSection from '../../../components/clientcomponents/AuthorSection';

async function getGuideData(slug) {
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/getguides/${slug}`, {
      cache: 'no-store'
    });
    
    if (!response.ok) {
      if (response.status === 404) {
        return { notFound: true };
      }
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const result = await response.json();
    
    if (!result.success || !result.data) {
      return { notFound: true };
    }
    
    return { guide: result.data };
  } catch (error) {
    console.error('Error fetching guide:', error);
    return { notFound: true };
  }
}

export async function generateMetadata({ params }) {
  const { slug } = await params;
  
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/api/frontend/getguides/${slug}`);
    
    if (!response.ok) {
      return {
        title: 'Guide Not Found - University Portal',
        description: 'The requested guide could not be found.'
      };
    }
    
    const result = await response.json();
    const guide = result.data;

    let seoData = {};
    
    if (guide.seo) {
      try {
        seoData = typeof guide.seo === 'string' ? JSON.parse(guide.seo) : guide.seo;
      } catch (e) {
        console.error('Error parsing SEO data:', e);
      }
    }
    
    const showMeta = seoData.show_meta !== 'off';
    const canonical_url = `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/guides/${guide.slug}`
    
    return {
      title: showMeta && seoData.meta_title ? seoData.meta_title : guide.title,
      description: showMeta && seoData.meta_description ? seoData.meta_description : (guide.short_description || guide.title),
      keywords: showMeta && seoData.meta_keywords ? seoData.meta_keywords : '',
      alternates: {
        canonical: canonical_url,
      },
      openGraph: {
        title: showMeta && seoData.meta_title ? seoData.meta_title : guide.title,
        description: showMeta && seoData.meta_description ? seoData.meta_description : (guide.short_description || guide.title),
        images: [guide.image || '/assets/placeholder-guide.png'],
        url: canonical_url,
        siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
        type: 'article',
      },
      twitter: {
        card: 'summary_large_image',
        title: showMeta && seoData.meta_title ? seoData.meta_title : guide.title,
        description: showMeta && seoData.meta_description ? seoData.meta_description : (guide.short_description || guide.title),
        site: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
        url: canonical_url,
        images: [guide.image || '/assets/placeholder-guide.png'],
      },
      robots: {
        index: true,
        follow: true,
        nocache: true,
      },
    };
  } catch (error) {
    console.error('Error generating metadata:', error);
    return {
      title: 'University Guides - University Portal',
      description: 'Comprehensive guides for students seeking education opportunities'
    };
  }
}

async function getRelatedGuides(currentGuideId) {
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/getguides?limit=3`);
    
    if (!response.ok) {
      return [];
    }
    
    const result = await response.json();
    const items = result.data || [];
    
    return items.filter(g => g.id !== currentGuideId).slice(0, 3);
  } catch (error) {
    console.error('Error fetching related guides:', error);
    return [];
  }
}

// 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}`;
};

export default async function GuideDetailPage({ params }) {
  const { slug } = await params;
  const { guide, notFound } = await getGuideData(slug);
  
  if (notFound) {
    notFound();
  }
  
  const relatedGuides = await getRelatedGuides(guide.id);
  
  // Format date
  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  // Estimated reading time
  const calculateReadingTime = (content) => {
    if (!content) return 5;
    const wordsPerMinute = 200;
    const textContent = content.replace(/<[^>]*>/g, '');
    const wordCount = textContent.split(/\s+/).length;
    return Math.max(1, Math.ceil(wordCount / wordsPerMinute));
  };

  const readingTime = calculateReadingTime(guide.description);

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <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-16 md:py-24">
          <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-6 animate-pulse">
              <Sparkles className="w-5 h-5" />
              Comprehensive Study Guide
            </div>

            <h1 className="text-4xl md:text-6xl font-bold text-gray-900 mb-6 leading-tight">
              {guide.title}
            </h1>

            <p className="text-lg md:text-xl text-gray-600 mb-8 max-w-3xl mx-auto leading-relaxed">
              {guide.short_description || 'Expert insights and comprehensive information to help you achieve your study abroad dreams'}
            </p>

            {/* Stats */}
            <div className="flex flex-wrap justify-center gap-6 mb-8">
              <div className="flex items-center gap-2 text-gray-700">
                <Clock className="w-5 h-5 text-teal-600" />
                <span className="font-semibold">{readingTime} min read</span>
              </div>
              <div className="flex items-center gap-2 text-gray-700">
                <Calendar className="w-5 h-5 text-blue-600" />
                <span className="font-semibold">{formatDate(guide.updated_at)}</span>
              </div>
              <div className="flex items-center gap-2 text-gray-700">
                <Globe className="w-5 h-5 text-emerald-600" />
                <span className="font-semibold">{guide.country || 'Global'}</span>
              </div>
            </div>

            {/* Breadcrumb */}
            <div className="flex items-center justify-center gap-2 text-sm text-gray-600">
              <Link href="/" className="hover:text-teal-600 transition-colors flex items-center gap-1">
                <Home className="w-4 h-4" />
                Home
              </Link>
              <ChevronRight className="w-4 h-4" />
              <Link href="/guides" className="hover:text-teal-600 transition-colors">
                Guides
              </Link>
              <ChevronRight className="w-4 h-4" />
              <span className="text-teal-700 font-semibold">{guide.title}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="pb-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid lg:grid-cols-1 gap-8">
            {/* Article Content - Full Width */}
            <div className="space-y-8 mt-10">

              {/* Featured Image with fixed aspect ratio */}
              {guide.image && (
                <ModernCard className="p-0 overflow-hidden">
                  <div className="relative aspect-video w-full">
                    <Image
                      src={
                        guide.image
                          ? getS3Url(guide.image)
                          : "/assets/placeholder-guide.png"
                      }
                      alt={guide.title || "Guide Image"}
                      fill
                      className="object-cover"
                      sizes="(max-width: 768px) 100vw, (max-width: 1200px) 80vw, 1200px"
                      priority
                      unoptimized={guide.image && guide.image.includes('s3.amazonaws.com')}
                    />
                    <div className="absolute inset-0 bg-linear-to-t from-black/70 via-black/30 to-transparent"></div>
                    <div className="absolute bottom-6 left-6 right-6">
                      <div className="max-w-3xl">
                        <div className=" items-center gap-2 bg-linear-to-r from-teal-600/80 to-blue-500/80 backdrop-blur-sm px-4 py-2 rounded-full mb-3 hidden md:inline-flex">
                          <Sparkles className="w-4 h-4" />
                          <span className="text-sm font-semibold text-white">Featured Guide</span>
                        </div>
                        <h3 className="text-2xl md:text-3xl font-bold text-white mb-2">{guide.title}</h3>
                        <p className="text-white/90 hidden md:block">{guide.short_description || 'Comprehensive study abroad information'}</p>
                      </div>
                    </div>
                  </div>
                </ModernCard>
              )}

              {/* Main Content */}
              <ModernCard className="p-8">
                <div className="prose prose-lg max-w-none">
                  <TextDisplay 
                    content={guide.description} 
                    className="sn-content guide-content text-gray-700"
                  />
                </div>
              </ModernCard>

              {/* Author Section */}
              <AuthorSection authorData={guide.author} />

              {/* Download CTA */}
              <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-8 text-center">
                <div className="max-w-2xl mx-auto">
                  <BookOpen className="w-12 h-12 text-white mx-auto mb-4" />
                  <h3 className="text-2xl font-bold text-white mb-4">Get Student Support Documents</h3>
                  <p className="text-white/80 mb-6">
                    Download all necessary documents and templates to streamline your application process
                  </p>
                  <a 
                    href="/student-support-documents" 
                    className="inline-flex items-center justify-center gap-2 bg-white/20 backdrop-blur-sm text-white font-semibold py-3 px-8 rounded-xl hover:bg-white/30 transition-all duration-300"
                  >
                    <FileText className="w-5 h-5" />
                    Download Documents
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Related Guides */}
      {relatedGuides.length > 0 && (
        <section className="py-16 bg-gray-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="text-center mb-12">
              <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-4">
                <Sparkles className="w-5 h-5" />
                Related Guides
              </div>
              <h2 className="text-3xl font-bold text-gray-900 mb-4">
                Explore More <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">Guides</span>
              </h2>
              <p className="text-gray-600 max-w-2xl mx-auto">
                Discover other comprehensive guides that might interest you
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {relatedGuides.map((g) => {
                const authorImageUrl = g.author?.image ? getS3Url(g.author.image) : null;
                
                return (
                  <div key={g.id} className="group h-full">
                    <div className="bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 overflow-hidden cursor-pointer border border-gray-100 hover:border-teal-200 h-full flex flex-col">
                      {/* Image with Link */}
                      <Link href={`/guides/${g.slug}`} className="block">
                        <div className="relative h-48 overflow-hidden">
                          <Image
                            src={
                              g.image
                                ? getS3Url(g.image)
                                : "/assets/placeholder-guide.png"
                            }
                            alt={g.title || "Guide Image"}
                            fill
                            className="object-cover transition-transform duration-700 group-hover:scale-110"
                            unoptimized={g.image && g.image.includes('s3.amazonaws.com')}
                          />
                          <div className="absolute inset-0 bg-linear-to-t from-black/60 via-transparent to-transparent"></div>
                          <div className="absolute bottom-4 left-4">
                            <div className="inline-flex items-center gap-2 bg-white/20 backdrop-blur-sm px-3 py-1 rounded-full">
                              <Globe className="w-3 h-3 text-white" />
                              <span className="text-xs font-semibold text-white">{g.country || 'Global'}</span>
                            </div>
                          </div>
                        </div>
                      </Link>
                      
                      <div className="p-6 flex flex-col grow">
                        {/* Title with Link */}
                        <Link href={`/guides/${g.slug}`} className="block mb-3">
                          <h3 className="font-bold text-lg mb-3 line-clamp-2 text-gray-900 group-hover:text-teal-600 transition-colors">
                            {g.title}
                          </h3>
                        </Link>
                        
                        {g.short_description && (
                          <p className="text-gray-600 text-sm line-clamp-3 mb-4 grow">
                            {g.short_description}
                          </p>
                        )}
                        
                        {/* Author Section */}
                        {g.author && g.author.name && (
                          <div className="flex items-center gap-2 mb-4 pt-4 border-t border-gray-100">
                            {authorImageUrl ? (
                              <Link 
                                href={`/author/${g.author.slug}`}
                                onClick={(e) => e.stopPropagation()}
                                className="relative w-6 h-6 rounded-full overflow-hidden flex-shrink-0"
                              >
                                <Image
                                  src={authorImageUrl}
                                  alt={g.author.name}
                                  fill
                                  className="object-cover"
                                  unoptimized={authorImageUrl.includes('s3.amazonaws.com')}
                                />
                              </Link>
                            ) : (
                              <Link 
                                href={`/author/${g.author.slug}`}
                                onClick={(e) => e.stopPropagation()}
                                className="w-6 h-6 rounded-full bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center flex-shrink-0"
                              >
                                <User className="w-3 h-3 text-teal-500" />
                              </Link>
                            )}
                            
                            <Link 
                              href={`/author/${g.author.slug}`}
                              onClick={(e) => e.stopPropagation()}
                              className="text-sm text-gray-700 hover:text-teal-600 transition-colors line-clamp-1"
                              title={g.author.name}
                            >
                              {g.author.name}
                            </Link>
                          </div>
                        )}
                        
                        {/* Meta Info */}
                        <div className="flex items-center justify-between text-xs text-gray-500 pt-4 border-t border-gray-100 mt-auto">
                          <div className="flex items-center gap-2">
                            <Clock className="w-3 h-3" />
                            <span>{calculateReadingTime(g.description)} min read</span>
                          </div>
                          <div className="flex items-center gap-1 text-teal-600 font-semibold">
                            Read More
                            <ChevronRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* CTA */}
            <div className="text-center mt-12">
              <Link 
                href="/guides"
                className="inline-flex items-center gap-2 px-8 py-4 rounded-xl font-semibold transition-all duration-300 transform hover:scale-105 bg-linear-to-r from-teal-600 to-blue-500 text-white hover:from-teal-700 hover:to-blue-600 shadow-lg hover:shadow-xl"
              >
                View All Guides
                <ChevronRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
              </Link>
            </div>
          </div>
        </section>
      )}
    </div>
  );
}