'use client';

import React, { useState, useEffect } from 'react';
import { 
  Calendar, 
  User, 
  Share2, 
  BookOpen, 
  MessageSquare,
  Heart,
  Eye,
  ArrowLeft,
  Newspaper,
  TrendingUp,
  Globe,
  GraduationCap,
  Clock,
  ArrowRight
} from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import AuthorSection from '../../../components/clientcomponents/AuthorSection';

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

interface NewsDetailPageProps {
  singleData: any;
  newsData: any;
  initialComments: any[];
  initialReplies: any[];
  articleId: string;
  authorData: any;
}

const NewsDetailPage: React.FC<NewsDetailPageProps> = ({
  singleData,
  newsData,
  authorData
}) => {
  const router = useRouter();
  const [isLiked, setIsLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(singleData?.data?.likes || 0);
  const [viewCount, setViewCount] = useState(singleData?.data?.views || 0);
  const [shareCount, setShareCount] = useState(0);
  const [readingTime, setReadingTime] = useState(0);

  const newsdata = singleData?.data;
  const relatedNews = newsData?.data || [];

  // Calculate reading time
  useEffect(() => {
    if (newsdata?.description) {
      const words = newsdata.description.replace(/<[^>]*>/g, '').split(/\s+/).length;
      const time = Math.ceil(words / 200); // 200 words per minute
      setReadingTime(time);
    }
  }, [newsdata]);

  // Simulate view count increment
  useEffect(() => {
    const timer = setTimeout(() => {
      setViewCount(prev => prev + 1);
    }, 3000);
    return () => clearTimeout(timer);
  }, []);

  const handleLike = async () => {
    if (isLiked) return;
    
    try {
      setIsLiked(true);
      setLikeCount(prev => prev + 1);
      
      // Here you would typically make an API call to update likes
      // await fetch(`/api/news/${newsdata.id}/like`, { method: 'POST' });
    } catch (error) {
      console.error('Error liking article:', error);
      setIsLiked(false);
      setLikeCount(prev => prev - 1);
    }
  };

  const handleShare = (platform: string) => {
    const url = window.location.href;
    const title = newsdata.title;
    const text = newsdata.short_description;

    let shareUrl = '';
    switch (platform) {
      case 'facebook':
        shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`;
        break;
      case 'twitter':
        shareUrl = `https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}&text=${encodeURIComponent(title)}`;
        break;
      case 'linkedin':
        shareUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`;
        break;
      case 'whatsapp':
        shareUrl = `https://wa.me/?text=${encodeURIComponent(`${title} - ${url}`)}`;
        break;
    }

    if (shareUrl) {
      window.open(shareUrl, '_blank', 'width=600,height=400');
      setShareCount(prev => prev + 1);
    }
  };

  const handleCopyLink = () => {
    navigator.clipboard.writeText(window.location.href);
    alert('Link copied to clipboard!');
    setShareCount(prev => prev + 1);
  };

  if (!newsdata) {
    return (
      <div className="min-h-screen bg-linear-to-b from-gray-50 to-white flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">📰</div>
          <p className="text-gray-600">Loading news article...</p>
        </div>
      </div>
    );
  }

  const newsImageUrl = getS3Url(newsdata.image);
  const authorImageUrl = authorData?.profile_image ? getS3Url(authorData.profile_image) : null;

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">

      {/* Main Content */}
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Article Header */}
        <div className="mb-8">
          {/* Category/Featured Badge */}
          <div className="flex items-center gap-3 mb-6">
            {newsdata.is_featured && (
              <div className="inline-flex items-center gap-2 bg-linear-to-r from-amber-100 to-orange-100 text-amber-800 px-4 py-2 rounded-full text-sm font-semibold">
                <TrendingUp className="w-3 h-3" />
                Featured News
              </div>
            )}
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-4 py-2 rounded-full text-sm font-semibold">
              <Newspaper className="w-3 h-3" />
              Education News
            </div>
          </div>

          <h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-6 leading-tight">
            {newsdata.title}
          </h1>
          
          <div className="flex flex-wrap items-center gap-4 text-gray-600 mb-6">
            {/* Author Info */}
            <div className="flex items-center gap-3">
              {authorImageUrl ? (
                <div className="relative w-10 h-10 rounded-full overflow-hidden">
                  <Image
                    src={authorImageUrl}
                    alt={authorData?.full_name || 'Author'}
                    fill
                    sizes="40px"
                    className="object-cover"
                    unoptimized={authorImageUrl.includes('s3.amazonaws.com')}
                  />
                </div>
              ) : (
                <div className="w-10 h-10 rounded-full bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center">
                  <User className="w-5 h-5 text-teal-500" />
                </div>
              )}
              <div>
                <div className="font-semibold text-gray-900">
                  {authorData?.full_name || 'News Desk'}
                </div>
                {authorData?.title && (
                  <div className="text-sm text-gray-500">{authorData.title}</div>
                )}
              </div>
            </div>

            {/* Date and Reading Time */}
            <div className="flex items-center gap-4 ml-auto">
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4" />
                <span className="font-medium">
                  {new Date(newsdata.created_at).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric'
                  })}
                </span>
              </div>
              
              {readingTime > 0 && (
                <div className="flex items-center gap-2">
                  <Clock className="w-4 h-4" />
                  <span className="font-medium">{readingTime} min read</span>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Featured Image */}
        {newsImageUrl && (
          <div className="mb-8 rounded-2xl overflow-hidden shadow-xl">
            <div className="relative h-100 w-full">
              <Image
                src={newsImageUrl}
                alt={newsdata.title}
                fill
                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 80vw, 800px"
                className="object-cover"
                priority
                unoptimized={newsImageUrl.includes('s3.amazonaws.com')}
              />
            </div>
            {newsdata.image_caption && (
              <div className="bg-gray-50 p-4 text-center text-sm text-gray-500 italic border-t">
                {newsdata.image_caption}
              </div>
            )}
          </div>
        )}

        {/* Article Content */}
        <div className="prose prose-lg max-w-none mb-12">
          <div 
            dangerouslySetInnerHTML={{ __html: newsdata.description || '' }}
            className="text-gray-700 leading-relaxed"
          />
        </div>

        {/* Author Bio */}
        {authorData && (
          <AuthorSection authorData={authorData} />
        )}

        <br />

        {/* Related News */}
        {relatedNews.length > 0 && (
        <div className="mb-12">
            <div className="flex items-center justify-between mb-6">
            <div>
                <h2 className="text-2xl font-bold text-gray-900">Related News</h2>
                <p className="text-gray-600 text-sm mt-1">More news articles you might be interested in</p>
            </div>
            <Link 
                href="/news" 
                className="inline-flex items-center gap-2 text-teal-600 hover:text-teal-700 font-medium text-sm group"
            >
                View all news
                <ArrowRight className="w-3 h-3 transition-transform group-hover:translate-x-1" />
            </Link>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {relatedNews.slice(0, 3).map((related) => {
                const relatedImageUrl = getS3Url(related.image);
                const relatedAuthorImageUrl = related.author_image ? getS3Url(related.author_image) : null;
                
                return (
                <Link 
                    key={related.id} 
                    href={`/news/${related.slug}`}
                    className="group block"
                >
                    <div className="bg-white rounded-xl shadow-md overflow-hidden hover:shadow-lg transition-all duration-300 border border-gray-100 h-full flex flex-col">
                    {/* Image Container */}
                    <div className="relative h-48 w-full overflow-hidden">
                        {relatedImageUrl ? (
                        <>
                            <Image
                            src={relatedImageUrl}
                            alt={related.title}
                            fill
                            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                            className="object-cover transition-transform duration-500 group-hover:scale-110"
                            unoptimized={relatedImageUrl.includes('s3.amazonaws.com')}
                            />
                            <div className="absolute inset-0 bg-linear-to-t from-black/50 via-black/20 to-transparent"></div>
                        </>
                        ) : (
                        <div className="w-full h-full bg-linear-to-br from-teal-100 to-blue-100 flex items-center justify-center">
                            <Newspaper className="w-12 h-12 text-teal-300" />
                        </div>
                        )}
                        
                        {/* Category Badge */}
                        <div className="absolute bottom-3 left-3">
                        <div className="bg-linear-to-r from-teal-600 to-blue-500 text-white text-xs font-semibold px-3 py-1.5 rounded-full">
                            <Newspaper className="w-3 h-3 inline-block mr-1" />
                            News
                        </div>
                        </div>
                    </div>
                    
                    {/* Content */}
                    <div className="p-5 flex-1 flex flex-col">
                        {/* Title */}
                        <h3 className="font-bold text-lg text-gray-900 group-hover:text-teal-600 transition-colors line-clamp-2 mb-3 leading-snug">
                        {related.title}
                        </h3>
                        
                        {/* Short Description */}
                        {related.short_description && (
                        <p className="text-gray-600 text-sm line-clamp-2 mb-4 flex-1">
                            {related.short_description}
                        </p>
                        )}
                        
                        {/* Author and Date Section */}
                        <div className="mt-auto pt-4 border-t border-gray-100">
                        <div className="flex items-center justify-between">
                            {/* Author Info */}
                            <div className="flex items-center gap-2">
                            {relatedAuthorImageUrl ? (
                                <div className="relative w-8 h-8 rounded-full overflow-hidden">
                                <Image
                                    src={relatedAuthorImageUrl}
                                    alt={related.author_name || 'Author'}
                                    fill
                                    sizes="32px"
                                    className="object-cover"
                                    unoptimized={relatedAuthorImageUrl.includes('s3.amazonaws.com')}
                                />
                                </div>
                            ) : (
                                <div className="w-8 h-8 rounded-full bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center">
                                <User className="w-4 h-4 text-teal-500" />
                                </div>
                            )}
                            
                            <div>
                                <div className="font-medium text-sm text-gray-900 line-clamp-1">
                                {related.author_name || 'News Desk'}
                                </div>
                            </div>
                            </div>
                            
                            {/* Date */}
                            <div className="flex items-center gap-1.5 text-gray-500 text-xs">
                            <Calendar className="w-3.5 h-3.5" />
                            <span className="font-medium whitespace-nowrap">
                                {new Date(related.created_at).toLocaleDateString('en-US', {
                                month: 'short',
                                day: 'numeric'
                                })}
                            </span>
                            </div>
                        </div>
                        </div>
                    </div>
                    </div>
                </Link>
                );
            })}
            </div>
            
            {/* View All News Link (Mobile) */}
            <div className="mt-8 text-center md:hidden">
            <Link 
                href="/news" 
                className="inline-flex items-center gap-2 bg-linear-to-r from-teal-600 to-blue-500 text-white font-medium py-3 px-6 rounded-xl hover:opacity-90 transition-all duration-300"
            >
                <Newspaper className="w-4 h-4" />
                View All News Articles
            </Link>
            </div>
        </div>
        )}
      </div>

      {/* CTA Section */}
      <div className="py-12 bg-linear-to-r from-teal-50/50 to-blue-50/50">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-white rounded-2xl p-8 shadow-lg border border-gray-100">
            <div className="text-center">
              <h2 className="text-2xl font-bold text-gray-900 mb-4">
                Stay Updated with Education News
              </h2>
              <p className="text-gray-600 mb-6 max-w-2xl mx-auto">
                Subscribe to our newsletter and get the latest education news, scholarship alerts, 
                and university updates directly in your inbox.
              </p>
              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                <Link
                  href="/contact"
                  className="inline-flex items-center justify-center gap-2 bg-linear-to-r from-teal-600 to-blue-500 text-white font-semibold py-3 px-8 rounded-xl hover:opacity-90 transition-all duration-300"
                >
                  <Newspaper className="w-4 h-4" />
                  Contact Us
                </Link>
                <Link
                  href="/news"
                  className="inline-flex items-center justify-center gap-2 border-2 border-teal-600 text-teal-600 font-semibold py-3 px-8 rounded-xl hover:bg-teal-50 transition-all duration-300"
                >
                  <Globe className="w-4 h-4" />
                  Explore More News
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default NewsDetailPage;