import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import ConsultantDetailClient from './ConsultantDetailClient';

interface Consultant {
  id: number;
  name: string;
  company_name: string;
  email: string | null;
  phone: string | null;
  city: string;
  state: string;
  average_rating: number;
  rating_count: number;
  services: string[];
  response_time: string;
  digital_only: boolean;
  profile_picture: string | null;
  consultation_fee: number;
  consultation_currency: string;
  specialization: string[];
  target_countries: string[];
  languages: string[];
  website: string | null;
  experience_years: number | null;
  verified: boolean;
  bio: string | null;
  education_background: string[];
  certifications: string[];
  success_rate: number | null;
  total_students_helped: number | null;
  office_hours: string | null;
  consultation_modes: string[];
  seo_slug: string | null;
  seo_title: string | null;
  seo_description: string | null;
  seo_keywords: string | null;
}

async function fetchConsultantBySlug(slug: string): Promise<Consultant | null> {
  try {
    // Always use the unified API endpoint
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/consultants/${slug}`,
      { 
        method: 'GET',
        cache: 'no-store'
      }
    );
    
    if (!response.ok) {
      console.error(`API returned ${response.status}: ${response.statusText}`);
      return null;
    }
    
    const data = await response.json();
    
    if (data.success) {
      return data.data;
    } else {
      console.error('API returned error:', data.message);
      return null;
    }
    
  } catch (error) {
    console.error('Error fetching consultant:', error);
    return null;
  }
}

type Props = {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const consultant = await fetchConsultantBySlug(slug);
  
  if (!consultant) {
    return {
      title: 'Consultant Not Found',
      description: 'The consultant you are looking for does not exist.',
      robots: {
        index: false,
        follow: false,
      }
    };
  }

  // Use consultant's SEO data if available, otherwise generate from consultant info
  const title = consultant.seo_title || 
    `${consultant.company_name} - Study Abroad Consultant | ${process.env.NEXT_PUBLIC_APP_WEBSITE_NAME}`;
  
  const description = consultant.seo_description || 
    `Consult with ${consultant.company_name}, a ${consultant.specialization?.join(', ')} expert with ${consultant.experience_years || 0}+ years experience. Get professional guidance for your study abroad journey.`;
  
  const keywords = consultant.seo_keywords || '';
  
  const metadata: Metadata = {
    title,
    description,
    openGraph: {
      title,
      description,
      url: `${process.env.NEXT_PUBLIC_APP_URL}/consultant/${consultant.seo_slug || consultant.id}`,
      siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
      locale: 'en_US',
      type: 'website',
      images: consultant.profile_picture ? [{
        url: consultant.profile_picture,
        width: 800,
        height: 600,
        alt: consultant.company_name,
      }] : undefined,
    },
    twitter: {
      card: 'summary_large_image',
      title,
      description,
      images: consultant.profile_picture ? [consultant.profile_picture] : undefined,
    },
    alternates: {
      canonical: `${process.env.NEXT_PUBLIC_APP_URL}/consultant/${consultant.seo_slug || consultant.id}`,
    },
    robots: {
      index: true,
      follow: true,
      googleBot: {
        index: true,
        follow: true,
        'max-video-preview': -1,
        'max-image-preview': 'large',
        'max-snippet': -1,
      },
    },
  };

  // Add keywords only if they exist
  if (keywords) {
    metadata.keywords = keywords.split(',').map(k => k.trim());
  }

  return metadata;
}

export default async function ConsultantDetailPage({ params }: Props) {
  const { slug } = await params;
  const consultant = await fetchConsultantBySlug(slug);
  
  if (!consultant) {
    notFound();
  }
  
  return <ConsultantDetailClient consultant={consultant} />;
}