import React from 'react';
import NewsDetailPage from './NewsDetailPage';
import Link from 'next/link';

async function fetchData(slug) {
  try {
    const [singleResponse, newsResponse] = await Promise.all([
      fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/news/singlenews/`, {
        method: "POST",
        body: JSON.stringify({ slug }),
      }),
      fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/news?slug=${slug}`)
    ]);

    if (!singleResponse.ok || !newsResponse.ok) {
      throw new Error('Failed to fetch data');
    }

    const [singleData, newsData] = await Promise.all([
      singleResponse.json(),
      newsResponse.json()
    ]);

    return { singleData, newsData };
  } catch (error) {
    console.error('Error fetching data:', error);
    return { singleData: null, newsData: null };
  }
}

const FAQSchema = ({ singleData }) => {
  const newsdata = singleData?.data;
  
  // Early return if no data
  if (!newsdata) {
    return null;
  }

  // Check if FAQ data exists
  const hasSmQuestion = newsdata.sm_question !== undefined && newsdata.sm_question !== null;
  const hasSmAnswer = newsdata.sm_answer !== undefined && newsdata.sm_answer !== null;
  
  // Return null if either is missing
  if (!hasSmQuestion || !hasSmAnswer) {
    return null;
  }

  // Parse questions and answers
  let questions = [];
  let answers = [];
  
  try {
    questions = typeof newsdata.sm_question === 'string' 
      ? JSON.parse(newsdata.sm_question) 
      : newsdata.sm_question;
    
    answers = typeof newsdata.sm_answer === 'string' 
      ? JSON.parse(newsdata.sm_answer) 
      : newsdata.sm_answer;
  } catch (error) {
    console.error('Error parsing FAQ data:', error);
    return null;
  }

  // Ensure questions and answers are arrays
  if (!Array.isArray(questions) || !Array.isArray(answers)) {
    return null;
  }

  // Return null if arrays are empty
  if (questions.length === 0 || answers.length === 0) {
    return null;
  }

  // Create FAQ schema - only include valid question-answer pairs
  const mainEntity = [];
  
  for (let i = 0; i < Math.min(questions.length, answers.length); i++) {
    const question = questions[i];
    const answer = answers[i];
    
    // Only include if both question and answer exist and are non-empty
    if (question && answer && typeof question === 'string' && typeof answer === 'string') {
      mainEntity.push({
        "@type": "Question",
        "name": question.trim(),
        "acceptedAnswer": {
          "@type": "Answer",
          "text": answer.trim().replace(/\\r\\n/g, '\n')
        }
      });
    }
  }
  
  // Return null if no valid FAQ items
  if (mainEntity.length === 0) {
    return null;
  }

  const faqSchema = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    "mainEntity": mainEntity
  };

  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(faqSchema) }}
    />
  );
};

// Updated NewsArticle Schema
const NewsArticleSchema = ({ singleData }) => {
  // Extract newsdata from singleData
  const newsdata = singleData?.data;
  
  if (!newsdata) {
    return null;
  }

  // Parse SEO data
  let seo = [];
  if (newsdata?.seo) {
    try {
      seo = typeof newsdata.seo === 'string' ? JSON.parse(newsdata.seo) : newsdata.seo;
    } catch (e) {
      console.error('Error parsing SEO data:', e);
    }
  }

  // Determine title and description
  const showMeta = seo.show_meta !== 'off';
  const news_title = showMeta && seo.meta_title ? seo.meta_title : newsdata.title;
  const news_description = showMeta && seo.meta_description ? seo.meta_description : newsdata.description;

  // Get author information
  const author = newsdata.author;
  
  // Create NewsArticle schema
  const newsArticleSchema = {
    "@context": "https://schema.org",
    "@type": "NewsArticle",
    "headline": news_title,
    "description": news_description,
    "image": newsdata.image ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${newsdata.image}` : `${process.env.NEXT_PUBLIC_APP_URL}/assets/hero.webp`,
    "datePublished": newsdata.created_at || new Date().toISOString(),
    "dateModified": newsdata.updated_at || newsdata.created_at || new Date().toISOString(),
    "mainEntityOfPage": {
      "@type": "WebPage",
      "@id": `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/news/${newsdata.slug}`
    },
    "publisher": {
      "@type": "Organization",
      "name": "Universities Page",
      "logo": {
        "@type": "ImageObject",
        "url": "https://universitiespage.com/assets/logo.png"
      }
    },
    // NewsArticle specific fields
    "articleSection": "Education News",
    "keywords": ["education", "university", "study abroad", "scholarships", "academic news"]
  };

  // Add author information if available
  if (author && author.full_name) {
    newsArticleSchema.author = {
      "@type": "Person",
      "name": author.full_name,
      "url": author.slug ? `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/author/${author.slug}` : undefined
    };
  } else {
    // Fallback to organization if no author
    newsArticleSchema.author = {
      "@type": "Organization",
      "name": "Universities Page News Desk",
      "url": "https://universitiespage.com/"
    };
  }

  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(newsArticleSchema) }}
    />
  );
};

const AuthorSchema = ({ singleData }) => {
  // Extract newsdata from singleData
  const newsdata = singleData?.data;
  
  if (!newsdata || !newsdata.author || !newsdata.author.full_name) {
    return null;
  }

  const author = newsdata.author;
  
  // Create author schema
  const authorSchema = {
    "@context": "https://schema.org",
    "@type": "Person",
    "name": author.full_name,
    "description": author.bio || `News reporter at Universities Page`,
    "url": `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/author/${author.slug}`,
    "image": author.profile_image ? 
      `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${author.profile_image}` : 
      undefined,
    "sameAs": [
      author.website,
      author.social_facebook,
      author.social_twitter,
      author.social_instagram,
      author.social_linkedin
    ].filter(url => url && url.trim() !== ''),
    "knowsAbout": [
      "Education News",
      "University Updates",
      "Study Abroad News",
      "Scholarship Alerts",
      "Academic Policies"
    ],
    "memberOf": {
      "@type": "Organization",
      "name": "Universities Page"
    }
  };

  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(authorSchema) }}
    />
  );
};

export async function generateMetadata({ params }) {
  const { slug } = await params;
  
  try {
    const { singleData } = await fetchData(slug);
    
    if (!singleData?.data) {
      return {
        title: '404 - News Article Not Found',
        description: `The news article "${slug}" was not found.`,
        robots: { index: false, follow: false }
      };
    }

    const newsdata = singleData.data;
    let seo = [];
    
    if (newsdata?.seo) {
      try {
        seo = typeof newsdata.seo === 'string' ? JSON.parse(newsdata.seo) : newsdata.seo;
      } catch (e) {
        console.error('Error parsing SEO data:', e);
      }
    }

    const showMeta = seo.show_meta !== 'off';
    const canonical_url = `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/news/${newsdata.slug}`;
    const news_title = showMeta && seo.meta_title ? seo.meta_title : newsdata.title;
    const news_description = showMeta && seo.meta_description ? seo.meta_description : newsdata.description;
    const image_url = newsdata.image ? 
      `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${newsdata.image}` : 
      `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/assets/hero.webp`;

    // Get author for OpenGraph
    const authorName = newsdata.author?.full_name || 'Universities Page News Desk';

    return {
      title: news_title,
      description: news_description,
      alternates: { canonical: canonical_url },
      openGraph: {
        title: news_title,
        description: news_description,
        url: canonical_url,
        siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
        images: [{ url: image_url, width: 1900, height: 1080 }],
        locale: "en_US",
        type: "article",
        authors: [authorName],
        publishedTime: newsdata.created_at,
        modifiedTime: newsdata.updated_at || newsdata.created_at,
        section: "Education News",
        tags: ["education", "university", "study abroad", "scholarships"]
      },
      twitter: {
        card: "summary_large_image",
        title: news_title,
        description: news_description,
        site: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
        images: [{ url: image_url, width: 1900, height: 1080 }],
        creator: authorName,
      },
      robots: {
        index: true,
        follow: true,
        googleBot: {
          index: true,
          follow: true,
          'max-video-preview': -1,
          'max-image-preview': 'large',
          'max-snippet': -1,
        },
      },
      // Add author metadata if available
      ...(newsdata.author?.full_name && {
        authors: [{ name: newsdata.author.full_name }],
      }),
    };
  } catch (error) {
    return {
      title: 'Error Loading News Article',
      robots: { index: false },
    };
  }
}

const page = async ({ params }) => {
  const { slug } = await params;

  try {
    const { singleData, newsData } = await fetchData(slug);
    
    // Handle 404 - News article not found
    if (!singleData?.data) {
      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>
            <h1 className="text-2xl font-bold text-gray-900 mb-2">News Article Not Found</h1>
            <p className="text-gray-600 mb-6">The news article you're looking for doesn't exist or has been removed.</p>
            <Link 
              href="/news" 
              className="inline-flex items-center gap-2 px-6 py-3 bg-linear-to-r from-teal-600 to-blue-500 text-white rounded-xl font-medium hover:opacity-90 transition-all duration-300"
            >
              Back to News
            </Link>
          </div>
        </div>
      );
    }

    // Extract author data from singleData
    const authorData = singleData.data.author || null;

    return (
      <>
        <NewsArticleSchema singleData={singleData} />
        <FAQSchema singleData={singleData} />
        <AuthorSchema singleData={singleData} />
        <NewsDetailPage 
          singleData={singleData} 
          newsData={newsData}
          articleId={singleData.data.id}
          authorData={authorData}
        />
      </>
    );
  } catch (error) {
    console.error('Error loading news article:', error);
    
    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>
          <h1 className="text-2xl font-bold text-gray-900 mb-2">Error Loading News</h1>
          <p className="text-gray-600 mb-6">Failed to load the news article. Please try again.</p>
          <Link 
            href="/news" 
            className="inline-flex items-center gap-2 px-6 py-3 bg-linear-to-r from-teal-600 to-blue-500 text-white rounded-xl font-medium hover:opacity-90 transition-all duration-300"
          >
            Back to News
          </Link>
        </div>
      </div>
    );
  }
}

export default page;