'use client';

import React, { useState, useEffect } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import {
  BookOpen,
  Globe,
  Calendar,
  ArrowRight,
  Users,
  Award,
  MessageSquare,
  Mail,
  Phone,
  Facebook,
  Twitter,
  Instagram,
  Linkedin,
  ExternalLink,
  Clock
} from 'lucide-react';

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

const CONTENT_PER_PAGE = 6;

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

// Types
interface AuthorStats {
  articles: number;
  guides: number;
  totalContent: number;
}

interface Author {
  id: number;
  full_name: string;
  slug: string;
  bio: string;
  profile_image: string;
  website: string;
  social_facebook: string;
  social_twitter: string;
  social_instagram: string;
  social_linkedin: string;
  status: string;
  created_at: string;
  updated_at: string;
  stats: AuthorStats;
}

interface ContentItem {
  id: number;
  title: string;
  short_description?: string;
  sub_title?: string;
  description: string;
  image: string;
  slug: string;
  created_at: string;
  category_name?: string;
  is_featured?: boolean;
  [key: string]: any;
}

interface ContentData {
  articles: ContentItem[];
  guides: ContentItem[];
}

interface MetaData {
  totalItems: number;
  totalPages: number;
  currentPage: number;
  limit: number;
  hasNextPage: boolean;
  hasPrevPage: boolean;
}

interface AuthorDetailPageProps {
  initialData: {
    author: Author;
    content: ContentData;
    meta: MetaData;
  };
  slug: string;
  initialPage: number;
  initialTab: string;
}

const AuthorDetailPage = ({ 
  initialData, 
  slug, 
  initialPage, 
  initialTab 
}: AuthorDetailPageProps) => {
  const router = useRouter();
  const searchParams = useSearchParams();
  
  const [author] = useState<Author>(initialData.author);
  const [content, setContent] = useState<ContentData>(initialData.content);
  const [meta, setMeta] = useState<MetaData>(initialData.meta);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<string>(initialTab);
  const [currentPage, setCurrentPage] = useState<number>(initialPage);

  // Handle tab change
  const handleTabChange = (tab: string) => {
    setActiveTab(tab);
    setCurrentPage(1);
    
    const params = new URLSearchParams(searchParams.toString());
    params.set('tab', tab);
    params.set('page', '1');
    router.push(`?${params.toString()}`, { scroll: false });
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= meta.totalPages) {
      setCurrentPage(page);
      
      const params = new URLSearchParams(searchParams.toString());
      params.set('page', page.toString());
      router.push(`?${params.toString()}`, { scroll: false });
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  // Fetch data when URL params change
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(
          `/api/frontend/author/${slug}?page=${currentPage}&limit=${CONTENT_PER_PAGE}&contentType=${activeTab}`
        );
        
        if (!response.ok) {
          throw new Error('Failed to fetch author data');
        }
        
        const data = await response.json();
        
        if (data.success && data.data) {
          setContent(data.data.content);
          setMeta(data.data.meta);
        }
      } catch (error) {
        console.error('Error fetching author data:', error);
      } finally {
        setLoading(false);
      }
    };

    if (currentPage !== initialPage || activeTab !== initialTab) {
      fetchData();
    }
  }, [currentPage, activeTab, slug, initialPage, initialTab]);

  // Format date
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  // Calculate reading time
  const calculateReadingTime = (text: string) => {
    if (!text) return '2 min read';
    const words = text.split(' ').length;
    const minutes = Math.ceil(words / 200);
    return `${minutes} min read`;
  };

  // Stats for the author
  const authorStats = [
    { Icon: BookOpen, number: author.stats.articles.toString(), label: 'Articles Published', color: 'teal' },
    { Icon: Globe, number: author.stats.guides.toString(), label: 'Study Guides', color: 'blue' },
    { Icon: Users, number: author.stats.totalContent.toString(), label: 'Total Content', color: 'emerald' },
    { Icon: Award, number: '99%', label: 'Reader Satisfaction', color: 'amber' }
  ];

  const authorImageUrl = getS3Url(author.profile_image);
  const allContent = [...content.articles, ...content.guides];

  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(15)].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() * 80 + 40,
                height: Math.random() * 80 + 40,
                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="flex flex-col lg:flex-row items-center gap-8">
            {/* Author Image */}
            <div className="relative w-48 rounded-full h-48 lg:w-85 lg:h-128 lg:rounded-2xl overflow-hidden shadow-2xl">
              {authorImageUrl ? (
                <Image
                  src={authorImageUrl}
                  alt={author.full_name}
                  fill
                  className="object-cover"
                  unoptimized={authorImageUrl.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">
                  <Users className="w-16 h-16 text-teal-300" />
                </div>
              )}
            </div>

            {/* Author Info */}
            <div className="flex-1 text-center lg:text-left">
              <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-2 rounded-full text-sm font-semibold mb-4">
                <BookOpen className="w-4 h-4" />
                Expert Author
              </div>

              <h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
                {author.full_name}
              </h1>

              <p className="text-lg text-gray-600 mb-6">
                {author.bio || 'An experienced writer and educator passionate about helping students achieve their academic goals.'}
              </p>

              {/* Social Links */}
              <div className="flex items-center justify-center lg:justify-start gap-4 mb-6">
                {author.social_facebook && (
                  <a
                    href={author.social_facebook}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-full bg-white border border-gray-200 flex items-center justify-center text-gray-600 hover:text-blue-600 hover:border-blue-600 transition-all duration-300"
                  >
                    <Facebook className="w-5 h-5" />
                  </a>
                )}
                {author.social_twitter && (
                  <a
                    href={author.social_twitter}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-full bg-white border border-gray-200 flex items-center justify-center text-gray-600 hover:text-blue-400 hover:border-blue-400 transition-all duration-300"
                  >
                    <Twitter className="w-5 h-5" />
                  </a>
                )}
                {author.social_instagram && (
                  <a
                    href={author.social_instagram}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-full bg-white border border-gray-200 flex items-center justify-center text-gray-600 hover:text-pink-600 hover:border-pink-600 transition-all duration-300"
                  >
                    <Instagram className="w-5 h-5" />
                  </a>
                )}
                {author.social_linkedin && (
                  <a
                    href={author.social_linkedin}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-full bg-white border border-gray-200 flex items-center justify-center text-gray-600 hover:text-blue-700 hover:border-blue-700 transition-all duration-300"
                  >
                    <Linkedin className="w-5 h-5" />
                  </a>
                )}
                {author.website && (
                  <a
                    href={author.website}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-full bg-linear-to-r from-teal-600 to-blue-500 text-white flex items-center justify-center hover:opacity-90 transition-all duration-300"
                  >
                    <ExternalLink className="w-5 h-5" />
                  </a>
                )}
              </div>

              {/* Member Since */}
              <div className="flex items-center justify-center lg:justify-start gap-2 text-gray-500">
                <Calendar className="w-4 h-4" />
                <span>Member since {formatDate(author.created_at)}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Stats Section */}
      <div className="py-12">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-8">
            <h2 className="text-2xl font-bold text-gray-900 mb-2">
              Author&apos;s Impact
            </h2>
            <p className="text-gray-600">
              Contributions and achievements
            </p>
          </div>
          
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-6">
            {authorStats.map((stat, index) => (
              <div
                key={index}
                className="bg-white rounded-2xl p-4 md:p-6 shadow-lg border border-gray-100 text-center"
              >
                <div className={`inline-flex items-center justify-center w-12 h-12 rounded-full mb-3 ${
                  stat.color === 'teal' ? 'bg-linear-to-r from-teal-50 to-teal-100' :
                  stat.color === 'blue' ? 'bg-linear-to-r from-blue-50 to-blue-100' :
                  stat.color === 'emerald' ? 'bg-linear-to-r from-emerald-50 to-emerald-100' :
                  'bg-linear-to-r from-amber-50 to-amber-100'
                }`}>
                  <stat.Icon className={`w-6 h-6 ${
                    stat.color === 'teal' ? 'text-teal-600' :
                    stat.color === 'blue' ? 'text-blue-600' :
                    stat.color === 'emerald' ? 'text-emerald-600' :
                    'text-amber-600'
                  }`} />
                </div>
                <div className="text-2xl md:text-3xl font-bold text-gray-900 mb-1">
                  {stat.number}
                </div>
                <div className="text-sm text-gray-600">
                  {stat.label}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Content Section */}
      <div className="py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Tabs */}
          <div className="flex justify-center mb-12">
            <div className="inline-flex bg-gray-100 p-1 rounded-2xl">
              {['all', 'articles', 'guides'].map((tab) => (
                <button
                  key={tab}
                  onClick={() => handleTabChange(tab)}
                  className={`px-6 py-3 rounded-xl font-medium transition-all duration-300 capitalize ${
                    activeTab === tab
                      ? 'text-black font-bold shadow-lg'
                      : 'text-gray-700 hover:text-teal-600'
                  }`}
                  style={
                    activeTab === tab 
                      ? { 
                          background: 'linear-linear(135deg, #0ea5e9 0%, #06b6d4 100%)',
                          boxShadow: '0 4px 15px rgba(6, 182, 212, 0.3)'
                        } 
                      : {}
                  }
                >
                  {tab === 'all' ? 'All Content' : tab}
                </button>
              ))}
            </div>
          </div>

          {/* Content Grid */}
          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {[...Array(6)].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>
              ))}
            </div>
          ) : allContent.length > 0 ? (
            <>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                {allContent.map((item) => {
                  const isArticle = 'category_name' in item;
                  const itemImageUrl = getS3Url(item.image);
                  const readingTime = calculateReadingTime(isArticle ? item.description : item.description);
                  
                  return (
                    <Link 
                      key={item.id} 
                      href={isArticle ? `/${item.slug}` : `/guides/${item.slug}`}
                      className="block h-full"
                    >
                      <ModernCard className="group overflow-hidden hover:shadow-xl transition-all duration-300 cursor-pointer h-full flex flex-col">
                        {/* Image */}
                        <div className="relative h-48 w-full overflow-hidden">
                          {itemImageUrl ? (
                            <Image
                              src={itemImageUrl}
                              alt={item.title}
                              fill
                              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                              className="object-cover transition-transform duration-500 group-hover:scale-110"
                              unoptimized={itemImageUrl.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">
                              {isArticle ? (
                                <BookOpen className="w-12 h-12 text-teal-300" />
                              ) : (
                                <Globe className="w-12 h-12 text-teal-300" />
                              )}
                            </div>
                          )}
                          <div className="absolute inset-0 bg-linear-to-t from-black/70 via-black/30 to-transparent"></div>
                          
                          {/* Content Type Badge */}
                          <div className="absolute top-3 left-3 z-10">
                            <div className={`text-white text-xs font-semibold px-3 py-1.5 rounded-full ${
                              isArticle 
                                ? 'bg-linear-to-r from-teal-600 to-teal-500' 
                                : 'bg-linear-to-r from-blue-600 to-blue-500'
                            }`}>
                              {isArticle ? 'Article' : 'Guide'}
                            </div>
                          </div>
                        </div>
                        
                        {/* Content */}
                        <div className="p-6 grow flex flex-col">
                          <div className="flex justify-between items-start mb-3">
                            <h3 className="text-xl font-bold text-gray-900 leading-tight line-clamp-2">
                              {item.title}
                            </h3>
                            <ArrowRight className="w-5 h-5 text-gray-400 transition-transform group-hover:translate-x-2 shrink-0 mt-1" />
                          </div>
                          
                          {/* Meta Info */}
                          <div className="mt-4 pt-4 border-t border-gray-100 flex justify-between text-xs text-gray-500">
                            <div className="flex items-center gap-1">
                              <Clock className="w-3 h-3" />
                              {readingTime}
                            </div>
                            <div className="flex items-center gap-1">
                              <Calendar className="w-3 h-3" />
                              {formatDate(item.created_at)}
                            </div>
                          </div>
                        </div>
                      </ModernCard>
                    </Link>
                  );
                })}
              </div>

              {/* Pagination */}
              {meta.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, meta.totalPages) }, (_, i) => {
                      let pageNum;
                      if (meta.totalPages <= 5) {
                        pageNum = i + 1;
                      } else if (currentPage <= 3) {
                        pageNum = i + 1;
                      } else if (currentPage >= meta.totalPages - 2) {
                        pageNum = meta.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 === meta.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 className="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 Content Found
              </div>
              <p className="text-gray-500 max-w-md mx-auto mb-8">
                {activeTab === 'all' 
                  ? 'This author hasn\'t published any content yet.' 
                  : `This author hasn't published any ${activeTab} yet.`}
              </p>
              <Link 
                href="/blog" 
                className="inline-flex items-center gap-2 bg-linear-to-r from-teal-600 to-blue-500 text-white font-semibold py-3 px-6 rounded-xl hover:opacity-90 transition-all duration-300"
              >
                <BookOpen className="w-4 h-4" />
                Browse All Content
              </Link>
            </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">
              Need Expert Guidance?
            </h2>
            <p className="text-white/80 text-lg mb-8 max-w-2xl mx-auto">
              Our team of experienced authors and education consultants are here to help you achieve your academic goals.
            </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">
                <MessageSquare className="w-4 h-4" />
                Get Free Consultation
              </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" />
                Explore More Articles
              </Link>
            </div>
            
            {/* Contact Info */}
            <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"
                >
                  <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 AuthorDetailPage;