import React from 'react';
import ArticleDetailPage from '../../components/clientcomponents/ArticleDetailPage';
import Link from 'next/link';

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

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

    const [singleData, blogData] = await Promise.all([
      singleResponse.json(),
      blogsResponse.json()
    ]);

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

async function fetchCommentsAndReplies(articleId) {
  try {
    const [commentsResponse, repliesResponse] = await Promise.all([
      fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/comments?article_id=${articleId}&limit=200`),
      fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/replies?article_id=${articleId}`)
    ]);

    if (!commentsResponse.ok || !repliesResponse.ok) {
      throw new Error('Failed to fetch comments/replies');
    }

    const [commentsData, repliesData] = await Promise.all([
      commentsResponse.json(),
      repliesResponse.json()
    ]);

    return {
      comments: commentsData.data || [],
      replies: repliesData.data || []
    };
  } catch (error) {
    console.error('Error fetching comments/replies:', error);
    return {
      comments: [],
      replies: []
    };
  }
}

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

  // Check if FAQ data exists
  const hasSmQuestion = blogdata.sm_question !== undefined && blogdata.sm_question !== null;
  const hasSmAnswer = blogdata.sm_answer !== undefined && blogdata.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 blogdata.sm_question === 'string' 
      ? JSON.parse(blogdata.sm_question) 
      : blogdata.sm_question;
    
    answers = typeof blogdata.sm_answer === 'string' 
      ? JSON.parse(blogdata.sm_answer) 
      : blogdata.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) }}
    />
  );
};

const ArticleSchema = ({ singleData }) => {
  // Extract blogdata from singleData
  const blogdata = singleData?.data;
  
  if (!blogdata) {
    return null; // Return nothing if no data
  }

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

  // Determine title and description (same logic as generateMetadata)
  const showMeta = seo.show_meta !== 'off';
  const article_title = showMeta && seo.meta_title ? seo.meta_title : blogdata.title;
  const article_description = showMeta && seo.meta_description ? seo.meta_description : blogdata.short_description;

  // Get author information
  const author = blogdata.author;
  
  // Create article schema with author
  const articleSchema = {
    "@context": "https://schema.org",
    "@type": "Article",
    "headline": article_title,
    "description": article_description,
    "image": blogdata.image ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${blogdata.image}` : `${process.env.NEXT_PUBLIC_APP_URL}/assets/hero.webp`,
    "datePublished": blogdata.created_at || new Date().toISOString(),
    "dateModified": blogdata.updated_at || blogdata.created_at || new Date().toISOString(),
    "mainEntityOfPage": {
      "@type": "WebPage",
      "@id": `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/${blogdata.slug}`
    },
    "publisher": {
      "@type": "Organization",
      "name": "Universities Page",
      "logo": {
        "@type": "ImageObject",
        "url": "https://universitiespage.com/assets/logo.png"
      }
    }
  };

  // Add author information if available
  if (author && author.full_name) {
    articleSchema.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
    articleSchema.author = {
      "@type": "Organization",
      "name": "Universities Page",
      "url": "https://universitiespage.com/"
    };
  }

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

// New Author Schema component
const AuthorSchema = ({ singleData }) => {
  // Extract blogdata from singleData
  const blogdata = singleData?.data;
  
  if (!blogdata || !blogdata.author || !blogdata.author.full_name) {
    return null; // Return nothing if no author data
  }

  const author = blogdata.author;
  
  // Create author schema
  const authorSchema = {
    "@context": "https://schema.org",
    "@type": "Person",
    "name": author.full_name,
    "description": author.bio || `Expert author 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",
      "Study Abroad",
      "University Admissions",
      "Career Counseling",
      "Scholarships"
    ],
    "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 - Article Not Found',
        description: `The article "${slug}" was not found.`,
        robots: { index: false, follow: false }
      };
    }

    const blogdata = singleData.data;
    let seo = [];
    
    if (blogdata?.seo) {
      try {
        seo = typeof blogdata.seo === 'string' ? JSON.parse(blogdata.seo) : blogdata.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}/${blogdata.slug}`;
    const article_title = showMeta && seo.meta_title ? seo.meta_title : blogdata.title;
    const article_description = showMeta && seo.meta_description ? seo.meta_description : blogdata.short_description;
    const image_url = blogdata.image ? 
      `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${blogdata.image}` : 
      `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/assets/hero.webp`;

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

    return {
      title: article_title,
      description: article_description,
      alternates: { canonical: canonical_url },
      openGraph: {
        title: article_title,
        description: article_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: blogdata.created_at,
        modifiedTime: blogdata.updated_at || blogdata.created_at,
      },
      twitter: {
        card: "summary_large_image",
        title: article_title,
        description: article_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
      ...(blogdata.author?.full_name && {
        authors: [{ name: blogdata.author.full_name }],
      }),
    };
  } catch (error) {
    return {
      title: 'Error Loading Article',
      robots: { index: false },
    };
  }
}

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

  try {
    const { singleData, blogData } = await fetchData(slug);
    
    // Handle 404 - Article not found
    if (!singleData?.data) {
      return (
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <div className="text-red-500 text-2xl mb-4">⚠️</div>
            <p className="text-gray-600 mb-4">Article not found.</p>
            <Link 
              href="/blog" 
              className="inline-block px-6 py-3 bg-linear-to-r from-[#0B6F78] to-[#0a306b] text-white rounded-lg font-medium"
            >
              Back to Blog
            </Link>
          </div>
        </div>
      );
    }
    
    // Fetch comments and replies on the server
    const { comments, replies } = await fetchCommentsAndReplies(singleData.data.id);

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

    return (
      <>
        <ArticleSchema singleData={singleData} />
        <FAQSchema singleData={singleData} />
        <AuthorSchema singleData={singleData} />
        <ArticleDetailPage 
          singleData={singleData} 
          blogData={blogData}
          initialComments={comments}
          initialReplies={replies}
          articleId={singleData.data.id}
          authorData={authorData} // Pass author data to the component
        />
      </>
    );
  } catch (error) {
    console.error('Error loading article:', error);
    
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="text-red-500 text-2xl mb-4">⚠️</div>
          <p className="text-gray-600 mb-4">Failed to load article. Please try again.</p>
          <Link 
            href="/blog" 
            className="inline-block px-6 py-3 bg-linear-to-r from-[#0B6F78] to-[#0a306b] text-white rounded-lg font-medium"
          >
            Back to Blog
          </Link>
        </div>
      </div>
    );
  }
}

export default page;