import React from 'react'
import CourseDetailPage from '../../../components/clientcomponents/CourseDetailPage'
import { redirect, notFound } from 'next/navigation';
import Link from 'next/link';

async function fetchData(slug, course_slug) {
  const coursesResponse = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/getcoursedetails/${slug}/${course_slug}`, {
    method: "POST"
  });

  if (coursesResponse.status === 404) {
    return { error: 'NOT_FOUND' };
  }

  if (!coursesResponse.ok) {
    throw new Error(`HTTP error! status: ${coursesResponse.status}`);
  }

  const coursesData = await coursesResponse.json();

  return coursesData;
}

// Consultation Service Schema Component
const ConsultationServiceSchema = ({ coursesData, slug }) => {
  // Check if data exists before rendering schema
  if (!coursesData?.data) {
    return null;
  }

  const description = `${coursesData?.data?.name} ${coursesData?.data?.qualification} course is offered in ${coursesData?.data?.university_name} with the duration of ${coursesData?.data?.duration}${coursesData?.data?.language ? `, taught in ${coursesData?.data?.language}` : ''}. ${coursesData?.data?.yearly_fee ? `The tuition fees are $${coursesData?.data?.yearly_fee} yearly` : ''}${coursesData?.data?.intake ? ` and admission intake is ${coursesData?.data?.intake}` : ''}.`;
  
  const pageTitle = `${coursesData?.data?.name} ${coursesData?.data?.qualification} in ${coursesData?.data?.university_name}`;
  const currentUrl = `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/${coursesData?.data?.university_slug}/${slug}`;

  const consultationServiceSchema = {
    "@context": "https://schema.org",
    "@type": "Service",
    "name": pageTitle ? pageTitle : "Study Abroad Consultation",
    "description": description ? description : "Free professional consultation for studying abroad including university selection, application guidance, scholarship assistance, and visa processing.",
    "provider": {
      "@type": "Organization",
      "name": "Universities Page",
      "url": "https://universitiespage.com/",
      "logo": "https://universitiespage.com/assets/logo.png"
    },
    "areaServed": "PK",
    "serviceType": "Education Consulting",
    "category": "Educational Consultation",
    "offers": {
      "@type": "Offer",
      "price": coursesData?.data.consultation_fee_after_discount > 0 
                ? parseFloat(coursesData?.data.consultation_fee_after_discount).toFixed(2)
                : parseFloat(coursesData?.data.consultation_fee).toFixed(2),
      "priceCurrency": "PKR",
      "availability": "https://schema.org/InStock",
      "url": currentUrl
    },
    "mainEntityOfPage": {
      "@type": "WebPage",
      "@id": currentUrl
    }
  };

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

export async function generateMetadata({ params }) {
  const { slug, courseslug } = await params;

  try {
    const singleCourse = await fetchData(slug, courseslug);

    // Handle 404 in metadata generation
    if (singleCourse?.error === 'NOT_FOUND' || !singleCourse?.success) {
      return {
        title: 'Course Not Found - Universities Page',
        description: 'The requested course could not be found.',
        robots: {
          index: false,
          follow: false,
        },
      };
    }

    if (singleCourse?.course_slug && singleCourse?.university_slug) {
      const currentUrl = `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/${singleCourse?.data?.university_slug}/${courseslug}`;
      return {
        alternates: {
          canonical: currentUrl,
        },
      };
    }

    const description = `${singleCourse?.data?.name} ${singleCourse?.data?.qualification} course is offered in ${singleCourse?.data?.university_name} with the duration of ${singleCourse?.data?.duration}${singleCourse?.data?.language ? `, taught in ${singleCourse?.data?.language}` : ''}. ${singleCourse?.data?.yearly_fee ? `The tuition fees are $${singleCourse?.data?.yearly_fee} yearly` : ''}${singleCourse?.data?.intake ? ` and admission intake is ${singleCourse?.data?.intake}` : ''}.`;
    
    const pageTitle = `${singleCourse?.data?.name} ${singleCourse?.data?.qualification} in ${singleCourse?.data?.university_name}`;
    const imageUrl = `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${singleCourse?.data?.universityLogo}` || 'https://www.universitiespage.com/filemanager/photos/1/thumbs/5d98611365165.png';
    const currentUrl = `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/${singleCourse?.data?.university_slug}/${courseslug}`;

    return {
      title: pageTitle,
      description: description,
      image: {
        url: imageUrl,
      },
      siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
      alternates: {
        canonical: currentUrl,
      },
      openGraph: {
        title: pageTitle,
        description: description,
        url: currentUrl,
        siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
        images: [
          {
            url: imageUrl,
          },
        ],
        locale: "en_US",
        type: "website",
      },
      twitter: {
        card: "summary",
        title: pageTitle,
        description: description,
        site: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
        images: [
          {
            url: imageUrl
          },
        ],
      },
      robots: {
        index: true,
        follow: true,
        nocache: true,
      },
    };
  } catch (error) {
    return {
      title: 'Error Loading Course - Universities Page',
      description: 'There was an error loading the course details.',
      robots: {
        index: false,
        follow: false,
      },
    };
  }
}

// 404 Error Component
const NotFoundComponent = ({ universitySlug }) => {
  return (
    <div className="min-h-screen flex flex-col items-center justify-center bg-gray-50 px-4">
      <div className="max-w-md w-full text-center">
        <h1 className="text-6xl font-bold text-red-600 mb-4">404</h1>
        <h2 className="text-2xl font-semibold text-gray-800 mb-4">Course Not Found</h2>
        <p className="text-gray-600 mb-8">
          The course you're looking for doesn't exist or may have been moved.
        </p>
        
        <div className="space-y-4">
          <Link
            href={`/${universitySlug}`}
            className="inline-block bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-colors duration-200 font-medium"
          >
            View University Page
          </Link>
          
          <div>
            <Link
              href="/"
              className="inline-block text-blue-600 hover:text-blue-800 font-medium"
            >
              ← Back to Homepage
            </Link>
          </div>
        </div>
        
        <div className="mt-8 pt-8 border-t border-gray-200">
          <h3 className="text-lg font-medium text-gray-800 mb-4">Looking for something else?</h3>
          <p className="text-gray-600">
            Browse our complete list of universities and courses to find what you're looking for.
          </p>
        </div>
      </div>
    </div>
  );
};

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

  try {
    const coursesData = await fetchData(slug, courseslug);

    // Handle 404 - Course not found
    if (coursesData?.error === 'NOT_FOUND' || !coursesData?.success) {
      return <NotFoundComponent universitySlug={slug} />;
    }
  
    // Handle redirect for old URLs - do this before any JSX
    if (coursesData?.course_slug && coursesData?.university_slug) {
      if (coursesData.university_slug !== slug || coursesData.course_slug !== courseslug) {
        console.log("Redirecting to:", `/${coursesData?.university_slug}/${coursesData?.course_slug}`);
        redirect(`/${coursesData?.university_slug}/${coursesData?.course_slug}`);
      }
    }

    // If no redirect needed, render the page
    return (
      <div>
        <ConsultationServiceSchema coursesData={coursesData} slug={courseslug} />
        <CourseDetailPage s_course={coursesData} />
      </div>
    );
  } catch (error) {
    // Check if it's a redirect error - don't show error page for redirects
    if (error?.digest?.startsWith('NEXT_REDIRECT')) {
      throw error; // Re-throw redirect errors so Next.js can handle them
    }
    
    console.error('Error loading course:', error);
    
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-gray-50 px-4">
        <div className="max-w-md w-full text-center">
          <h1 className="text-6xl font-bold text-yellow-600 mb-4">500</h1>
          <h2 className="text-2xl font-semibold text-gray-800 mb-4">Server Error</h2>
          <p className="text-gray-600 mb-8">
            There was an error loading the course details. Please try again later.
          </p>
          <Link
            href="/"
            className="inline-block bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-colors duration-200 font-medium"
          >
            Go to Homepage
          </Link>
        </div>
      </div>
    );
  }
};

export default page;