'use client';

import React, { useState, useEffect } from 'react';
import { Search, Calendar, ArrowRight, Newspaper, TrendingUp, Globe, GraduationCap, BookOpen } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';

// Import Shared Components
import ModernCard from '../../components/shared/ModernCard';

const NEWS_PER_PAGE = 6;

interface News {
  id: string;
  title: string;
  slug: string;
  description: string;
  image: string;
  is_featured: boolean;
  likes: number;
  created_at: string;
  updated_at: string;
  author_name?: string;
  author_slug?: string;
  author_image?: string;
}

const NewsClient = () => {
  const [news, setNews] = useState<News[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [totalNews, setTotalNews] = useState(0);
  const [totalPages, setTotalPages] = useState(0);

  // Fetch news with server-side pagination
  const fetchNews = async (page = 1, search = '') => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        limit: NEWS_PER_PAGE.toString(),
        page: page.toString()
      });

      if (search.trim()) {
        params.append('search', search.trim());
      }

      const res = await fetch(`/api/frontend/news?${params.toString()}`);
      const data = await res.json();
      
      if (data && data.data) {
        setNews(data.data);
        
        let total = data.pagination?.totalItems || 0;
        setTotalNews(total);
        
        const calculatedPages = Math.ceil(total / NEWS_PER_PAGE);
        setTotalPages(calculatedPages);
      } else {
        setNews([]);
        setTotalNews(0);
        setTotalPages(0);
      }
    } catch (err) {
      console.error('Error fetching news:', err);
      setNews([]);
      setTotalNews(0);
      setTotalPages(0);
    } finally {
      setLoading(false);
    }
  };

  // Initial load
  useEffect(() => {
    fetchNews(1, '');
  }, []);

  // Reset to first page when search changes
  useEffect(() => {
    setCurrentPage(1);
    fetchNews(1, searchQuery);
  }, [searchQuery]);

  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
      fetchNews(page, searchQuery);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const handleSearch = () => {
    setCurrentPage(1);
    fetchNews(1, searchQuery);
  };

  // Handle Enter key press in search
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  // 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}`;
  };

  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-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">
              <Newspaper className="w-5 h-5" />
              Breaking Education News
            </div>

            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              Latest{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Education News
              </span>
            </h1>

            <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
              Stay informed with the most recent updates on universities, scholarships, 
              and education policies from around the world.
            </p>

            {/* Search Bar */}
            <div className="max-w-2xl mx-auto mt-8">
              <div className="relative flex items-center gap-2">
                <div className="grow relative">
                  <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 z-10" />
                  <input
                    type="text"
                    placeholder="Search news, topics, or keywords..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onKeyPress={handleKeyPress}
                    className="w-full pl-12 pr-4 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>
                <button
                  onClick={handleSearch}
                  className="bg-linear-to-r from-teal-600 to-blue-500 text-white px-6 py-4 rounded-xl hover:opacity-90 transition-all duration-300 font-semibold whitespace-nowrap"
                >
                  Search
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Features Section */}
      <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">
              What We Cover
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Comprehensive coverage of education news from around the globe
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <div className="bg-white p-6 rounded-2xl shadow-lg border border-gray-100">
              <div className="w-12 h-12 rounded-lg bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center mb-4">
                <Globe className="w-6 h-6 text-teal-600" />
              </div>
              <h3 className="text-lg font-bold text-gray-900 mb-2">Global Updates</h3>
              <p className="text-gray-600 text-sm">Latest education news from universities worldwide</p>
            </div>
            
            <div className="bg-white p-6 rounded-2xl shadow-lg border border-gray-100">
              <div className="w-12 h-12 rounded-lg bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center mb-4">
                <GraduationCap className="w-6 h-6 text-teal-600" />
              </div>
              <h3 className="text-lg font-bold text-gray-900 mb-2">Scholarship Alerts</h3>
              <p className="text-gray-600 text-sm">Timely updates on scholarship opportunities</p>
            </div>
            
            <div className="bg-white p-6 rounded-2xl shadow-lg border border-gray-100">
              <div className="w-12 h-12 rounded-lg bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center mb-4">
                <TrendingUp className="w-6 h-6 text-teal-600" />
              </div>
              <h3 className="text-lg font-bold text-gray-900 mb-2">Policy Changes</h3>
              <p className="text-gray-600 text-sm">Important updates on education policies</p>
            </div>
            
            <div className="bg-white p-6 rounded-2xl shadow-lg border border-gray-100">
              <div className="w-12 h-12 rounded-lg bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center mb-4">
                <BookOpen className="w-6 h-6 text-teal-600" />
              </div>
              <h3 className="text-lg font-bold text-gray-900 mb-2">Study Abroad</h3>
              <p className="text-gray-600 text-sm">News about international education opportunities</p>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content 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">
              Browse{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Latest News
              </span>
            </h2>
            <p className="text-gray-600 text-lg max-w-2xl mx-auto">
              {searchQuery ? `Showing results for "${searchQuery}"` : 'Stay updated with breaking news and important announcements'}
            </p>
          </div>

          {/* Results Info */}
          <div className="text-center mb-8">
            <p className="text-gray-600 mb-2">
              Latest education news
              {searchQuery && ` for "${searchQuery}"`}
            </p>
            <p className="font-semibold text-teal-600">
              Page {currentPage} of {totalPages || 1} • 
              Showing {(currentPage - 1) * NEWS_PER_PAGE + 1}-
              {Math.min(currentPage * NEWS_PER_PAGE, totalNews)} of {totalNews} news articles
            </p>
          </div>

          {/* News Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {loading ? (
              Array.from({ length: NEWS_PER_PAGE }).map((_, idx) => (
                <div key={idx} className="animate-pulse overflow-hidden rounded-2xl bg-white shadow-lg">
                  <div className="w-full h-48 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 mb-4"></div>
                    <div className="h-10 bg-gray-300 rounded"></div>
                  </div>
                </div>
              ))
            ) : news.length === 0 ? (
              <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 news found
                </div>
                <p className="text-gray-500 max-w-md mx-auto">
                  {searchQuery ? `No news articles match your search for "${searchQuery}". Try different keywords.` 
                    : 'No news articles are available yet. Check back soon!'}
                </p>
              </div>
            ) : (
              news.map((newsItem) => {
                const newsImageUrl = getS3Url(newsItem.image);
                const authorImageUrl = newsItem.author_image ? getS3Url(newsItem.author_image) : null;
                
                return (
                  <div key={newsItem.id} className="group h-full">
                    <ModernCard className="overflow-hidden hover:shadow-xl transition-all duration-300 cursor-pointer h-full flex flex-col">
                      {/* News Image with Link */}
                      <Link href={`/news/${newsItem.slug}`} className="block">
                        <div className="relative h-48 w-full overflow-hidden">
                          {newsImageUrl ? (
                            <>
                              <Image
                                src={newsImageUrl}
                                alt={newsItem.title || 'News Article'}
                                fill
                                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                                className="object-cover transition-transform duration-500 group-hover:scale-110"
                                unoptimized={newsImageUrl.includes('s3.amazonaws.com')}
                              />
                              <div className="absolute inset-0 bg-linear-to-t from-black/70 via-black/30 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>
                          )}
                          
                          {/* Featured Badge */}
                          {newsItem.is_featured && (
                            <div className="absolute top-3 left-3 z-10">
                              <div className="bg-linear-to-r from-amber-500 to-orange-500 text-white text-xs font-semibold px-3 py-1.5 rounded-full flex items-center gap-1">
                                <TrendingUp className="w-3 h-3" />
                                Featured
                              </div>
                            </div>
                          )}
                        </div>
                      </Link>
                      
                      {/* Content Section */}
                      <div className="p-6 grow flex flex-col">
                        {/* News Title with Link */}
                        <Link href={`/news/${newsItem.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">
                              {newsItem.title}
                            </h3>
                            <ArrowRight className="w-5 h-5 text-gray-400 transition-transform group-hover:translate-x-2 shrink-0 mt-1" />
                          </div>
                        </Link>
                        
                        {newsItem.description && (
                          <p className="text-gray-600 text-sm mt-2 line-clamp-3 grow">
                            {newsItem.description.replace(/<[^>]*>/g, '').substring(0, 150)}...
                          </p>
                        )}
                        
                        {/* Author and Date */}
                        <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 ? (
                              <div className="relative w-6 h-6 rounded-full overflow-hidden shrink-0">
                                <Image
                                  src={authorImageUrl}
                                  alt={newsItem.author_name || 'Author'}
                                  fill
                                  sizes="24px"
                                  className="object-cover"
                                  unoptimized={authorImageUrl.includes('s3.amazonaws.com')}
                                />
                              </div>
                            ) : (
                              <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">
                                <Newspaper className="w-3 h-3 text-teal-500" />
                              </div>
                            )}
                            
                            {/* Author Name */}
                            <span className="font-medium text-gray-600">
                              {newsItem.author_name || 'News Desk'}
                            </span>
                          </div>
                          
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {newsItem.created_at ? new Date(newsItem.created_at).toLocaleDateString('en-US', {
                              month: 'short',
                              day: 'numeric',
                              year: 'numeric'
                            }) : 'Recent'}
                          </span>
                        </div>
                      </div>
                    </ModernCard>
                  </div>
                );
              })
            )}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <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 */}
      <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">
              Never Miss Important Updates
            </h2>
            <p className="text-white/80 text-lg mb-8 max-w-2xl mx-auto">
              Subscribe to our news alerts and get the latest education news delivered directly to 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-white text-teal-700 font-semibold py-3 px-8 rounded-xl hover:bg-gray-100 transition-all duration-300 transform hover:scale-105"
              >
                <Newspaper className="w-4 h-4" />
                Subscribe to News Alerts
              </Link>
              <Link 
                href="/blog" 
                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" />
                Read Our Blog
              </Link>
            </div>
            
            {/* Contact Info - Matching Blog Page */}
            <div className="mt-12 pt-8 border-t border-white/20">
              <p className="text-white/80 mb-6">Have questions? Contact us directly</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"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path>
                  </svg>
                  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"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                  </svg>
                  Email Us
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default NewsClient;