import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import AuthorDetailPage from './AuthorDetailPage';

// Generate metadata
export async function generateMetadata({ 
  params 
}: { 
  params: Promise<{ slug: string }>
}): Promise<Metadata> {
  const { slug } = await params;
  
  try {
    // Fetch author details from API
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/author/${slug}`
    );
    
    if (!response.ok) {
      return {
        title: 'Author Not Found - UniversitiesPage',
        description: 'The requested author profile could not be found.',
      };
    }
    
    const data = await response.json();
    
    if (!data.success || !data.data?.author) {
      return {
        title: 'Author Not Found - UniversitiesPage',
        description: 'The requested author profile could not be found.',
      };
    }
    
    const author = data.data.author;
    
    return {
      title: `${author.full_name} - Expert Author | UniversitiesPage`,
      description: author.bio?.substring(0, 160) || `Explore articles and guides by ${author.full_name}, an expert education consultant at UniversitiesPage.`,
      openGraph: {
        title: `${author.full_name} - Expert Author`,
        description: author.bio?.substring(0, 160) || 'Education expert at UniversitiesPage',
        images: author.profile_image ? [{
          url: `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${author.profile_image.replace(/^\/+/, "")}`,
          width: 1200,
          height: 630,
          alt: author.full_name,
        }] : [],
        type: 'profile',
      },
      twitter: {
        card: 'summary_large_image',
        title: `${author.full_name} - Expert Author`,
        description: author.bio?.substring(0, 160) || 'Education expert at UniversitiesPage',
        images: author.profile_image ? [
          `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${author.profile_image.replace(/^\/+/, "")}`
        ] : [],
      },
    };
  } catch (error) {
    console.error('Error generating metadata:', error);
    return {
      title: 'Author Profile - UniversitiesPage',
      description: 'Explore articles and guides by our expert authors',
    };
  }
}

// Generate structured data (JSON-LD)
function generateStructuredData(author: any) {
  return {
    '@context': 'https://schema.org',
    '@type': 'Person',
    name: author.full_name,
    description: author.bio,
    image: author.profile_image ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${author.profile_image.replace(/^\/+/, "")}` : undefined,
    url: `${process.env.NEXT_PUBLIC_APP_URL}/author/${author.slug}`,
    sameAs: [
      author.social_facebook,
      author.social_twitter,
      author.social_instagram,
      author.social_linkedin,
      author.website,
    ].filter(Boolean),
    knowsAbout: ['Education', 'Study Abroad', 'University Admissions', 'Career Counseling'],
    memberOf: {
      '@type': 'Organization',
      name: 'UniversitiesPage',
      url: process.env.NEXT_PUBLIC_APP_URL,
    },
  };
}

// Fetch author data on server using API
async function getAuthorData(slug: string, page: number = 1, contentType: string = 'all', limit: number = 6) {
  try {
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/author/${slug}?page=${page}&limit=${limit}&contentType=${contentType}`
    );
    
    if (!response.ok) {
      return null;
    }
    
    const data = await response.json();
    
    if (data.success && data.data) {
      return data.data;
    }
    
    return null;
  } catch (error) {
    console.error('Error fetching author data from API:', error);
    return null;
  }
}

export default async function AuthorPage({ 
  params,
  searchParams
}: { 
  params: Promise<{ slug: string }>,
  searchParams: Promise<{ page?: string, tab?: string }>
}) {
  const { slug } = await params;
  const { page = '1', tab = 'all' } = await searchParams;
  
  const currentPage = parseInt(page, 10) || 1;
  const activeTab = ['all', 'articles', 'guides'].includes(tab) ? tab : 'all';
  
  const data = await getAuthorData(slug, currentPage, activeTab);
  
  if (!data) {
    notFound();
  }
  
  const structuredData = generateStructuredData(data.author);
  
  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
      />
      <AuthorDetailPage 
        initialData={data}
        slug={slug}
        initialPage={currentPage}
        initialTab={activeTab}
      />
    </>
  );
}