import React from 'react'
import UniversityDetails from '../../../components/clientcomponents/UniversityDetails'

// Enhanced fetch functions with better error handling
async function fetchUniversityData(slug) {
  try {
    const uniResponse = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/universitydetails/${slug}`, { 
      method: 'POST',
      cache: 'no-store',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    if (!uniResponse.ok) {
      throw new Error(`University API responded with status: ${uniResponse.status}`);
    }
    
    return await uniResponse.json();
  } catch (error) {
    console.error('Error fetching university data:', error);
    throw new Error('Failed to load university information');
  }
}

async function fetchSubjectsData() {
  try {
    const subjectsResponse = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/getsubject`, {
      method: 'POST',
      cache: 'no-store',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    if (!subjectsResponse.ok) {
      // Return empty subjects array instead of throwing error
      console.warn('Subjects API failed, using empty subjects array');
      return { data: [] };
    }
    
    return await subjectsResponse.json();
  } catch (error) {
    console.error('Error fetching subjects data:', error);
    // Return empty subjects array to prevent page crash
    return { data: [] };
  }
}

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

  try {
    const uniData = await fetchUniversityData(slug);

    if(!uniData.success){
      return {
        title: '404 Page Not Found',
        description: '404 Page Not Found',
        robots: {
          index: false,
          follow: false,
          nocache: true,
        },
      };
    }

    const u_description = `${uniData.data.name} ${uniData.data.country} offers admission and scholarships ${new Date().getFullYear()} in total ${uniData.courses_count} courses. Check courses tution fees and these courses are taught in ${uniData.data.language} language.`

    const u_title = `${uniData.data.name} Admission, Scholarship & courses Fee ${new Date().getFullYear()}`;

    const canonical_url = `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/university/${uniData.data.slug}`

    return {
      title: u_title,
      description: u_description,
      icons: {
        icon: "/assets/fav.png",
      },
      image: {
        url: uniData?.data?.feature_image ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${uniData.data.feature_image}` : `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/assets/details.webp`,
        width: 1900,
        height: 1080,
      },
      siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
      alternates: {
        canonical: canonical_url,
      },
      openGraph: {
        title: u_title,
        description: u_description,
        url: canonical_url,
        siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
        images: [
          {
            url: uniData?.data?.feature_image ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${uniData.data.feature_image}` : `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/assets/details.webp`,
            width: 1900,
            height: 1080,
          },
        ],
        locale: "en_US",
        type: "website",
      },
      twitter: {
        card: "summary",
        title: u_title,
        description: u_description,
        site: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
        images: [
          {
            url: uniData?.data?.feature_image ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${uniData.data.feature_image}` : `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/assets/details.webp`,
            width: 1900,
            height: 1080,
          },
        ],
      },
      robots: {
        index: true,
        follow: true,
        nocache: true,
      },
    };
  } catch (error) {
    return {
      title: '404 Page Not Found',
      description: '404 Page Not Found',
      robots: {
        index: false,
        follow: false,
        nocache: true,
      },
    };
  }
}

// Consultation Service Schema Component
const ConsultationServiceSchema = ({uniData}) => {

  const u_description = `${uniData.data.name} ${uniData.data.country} offers admission and scholarships ${new Date().getFullYear()} in total ${uniData.courses_count} courses. Check courses tution fees and these courses are taught in ${uniData.data.languages} language.`

  const u_title = `${uniData.data.name} Admission,Scholarship & courses Fee ${new Date().getFullYear()}`;

  const currentUrl = `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/university/${uniData.data.slug}`

  const consultationServiceSchema = {
    "@context": "https://schema.org",
    "@type": "Service",
    "name": u_title ? u_title : "Study Abroad Consultation",
    "description": u_description ? u_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": uniData.data.consultation_fee_after_discount > 0 
                ? parseFloat(uniData.data.consultation_fee_after_discount).toFixed(2)
                : parseFloat(uniData.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) }}
    />
  );
};

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

  try {
    // Parallel data fetching - both requests happen simultaneously
    const [uniData, subjectsData] = await Promise.all([
      fetchUniversityData(slug),
      fetchSubjectsData()
    ]);

    // Check if university data is valid
    if (!uniData.success) {
      throw new Error(uniData.message || 'University not found');
    }

    return (
      <div>
        {/* Add Consultation Service Schema */}
        <ConsultationServiceSchema uniData={uniData} />
        
        <UniversityDetails 
          uniData={uniData} 
          subjectsData={subjectsData}
        />
      </div>
    )
  } catch (error) {
    console.error('Page error:', error);
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center max-w-md mx-auto p-6">
          <div className="text-6xl mb-4">🏫</div>
          <h1 className="text-2xl font-bold text-gray-800 mb-4">University Not Found</h1>
          <p className="text-gray-600 mb-6">
            {error.message || "The university you're looking for doesn't exist or may have been moved."}
          </p>
          <a 
            href="/"
            className="inline-block bg-[#0B6F78] text-white px-6 py-3 rounded-lg hover:bg-[#0a5a62] transition-colors"
          >
            Back to Homepage
          </a>
        </div>
      </div>
    );
  }
}

export default page