import { notFound } from 'next/navigation';
import DetailStudentPage from './DetailStudentPage';

const API_BASE_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

export async function generateMetadata({ params }) {
  try {
    const { slug } = await params;
    const response = await fetch(`${API_BASE_URL}/api/frontend/foreign-students/${slug}`, {
      next: { revalidate: 3600 } // Revalidate every hour for metadata
    });
    
    if (!response.ok) {
      return {
        title: 'Student Not Found | Foreign Student Guide',
        description: 'The requested student profile could not be found.',
      };
    }
    
    const data = await response.json();
    
    if (!data.success || !data.student) {
      return {
        title: 'Student Not Found | Foreign Student Guide',
        description: 'The requested student profile could not be found.',
      };
    }
    
    const student = data.student;
    
    // Helper function for image URL
    const getImageUrl = (imagePath) => {
      if (!imagePath) return null;
      
      if (imagePath.startsWith('http')) {
        return imagePath;
      }
      
      const cleanPath = imagePath.startsWith('/') ? imagePath.slice(1) : imagePath;
      return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${cleanPath}`;
    };
    
    const imageUrl = getImageUrl(student.profile_picture);
    const description = student.about_me 
      ? student.about_me.substring(0, 160) + '...'
      : `Connect with ${student.name}, an international student from ${student.country_name}. Hourly rate: $${student.hour_rate}`;
    
    return {
      title: `${student.name} | Foreign Student Guide`,
      description,
      authors: [{ name: student.name }],
      openGraph: {
        title: `${student.name} | Foreign Student Guide`,
        description,
        type: 'profile',
        url: `${process.env.NEXT_PUBLIC_APP_URL}/foreign-students/${slug}`,
        images: imageUrl ? [{
          url: imageUrl,
          width: 1200,
          height: 630,
          alt: `${student.name} profile picture`,
        }] : [
          {
            url: `${process.env.NEXT_PUBLIC_APP_URL}/og-default.jpg`,
            width: 1200,
            height: 630,
            alt: 'Foreign Student Guide',
          }
        ],
        profile: {
          firstName: student.name.split(' ')[0],
          lastName: student.name.split(' ').slice(1).join(' '),
          username: slug,
        },
      },
      twitter: {
        card: imageUrl ? 'summary_large_image' : 'summary',
        title: `${student.name} | Foreign Student Guide`,
        description,
        images: imageUrl ? [imageUrl] : [],
        creator: '@yourtwitterhandle',
      },
      robots: {
        index: true,
        follow: true,
        googleBot: {
          index: true,
          follow: true,
          'max-video-preview': -1,
          'max-image-preview': 'large',
          'max-snippet': -1,
        },
      },
      alternates: {
        canonical: `${process.env.NEXT_PUBLIC_APP_URL}/foreign-students/${slug}`,
      },
    };
  } catch (error) {
    console.error('Error generating metadata:', error);
    return {
      title: 'Student Profile | Foreign Student Guide',
      description: 'Connect with international students and cultural guides.',
    };
  }
}

async function fetchStudentDetails(slug) {
  try {
    const response = await fetch(`${API_BASE_URL}/api/frontend/foreign-students/${slug}`);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('Error fetching student details:', error);
    return { success: false, message: error.message };
  }
}

export default async function ForeignStudentDetailPage({ params }) {
  const { slug } = await params;
  
  try {
    const studentData = await fetchStudentDetails(slug);
    
    if (!studentData.success || !studentData.student) {
      notFound();
    }
    
    return (
      <DetailStudentPage 
        initialStudent={studentData.student}
        initialAvailability={studentData.availability || []}
        slug={slug}
      />
    );
  } catch (error) {
    console.error('Error in server component:', error);
    notFound();
  }
}