import { Metadata } from 'next'
import BlogPostPageClient from './BlogPostPageClient'

// API base URL - adjust based on your environment
const API_URL = process.env.NEXT_PUBLIC_BLOG_API_URL || 'https://accountant.aktivrs.com'

async function getPost(slugOrId: string) {
  try {
    // Check if it's a numeric ID
    const postId = parseInt(slugOrId, 10)
    const isNumericId = !isNaN(postId)

    const endpoint = isNumericId
      ? `${API_URL}/api/blogs/${postId}`
      : `${API_URL}/api/blogs/slug/${slugOrId}`

    console.log('Fetching blog post from:', endpoint)

    const res = await fetch(endpoint, {
      cache: 'no-store',
      headers: {
        'Accept': 'application/json',
      }
    })

    if (!res.ok) {
      console.error('Failed to fetch post:', res.status, res.statusText)
      return null
    }

    const data = await res.json()
    console.log('Blog post data:', JSON.stringify(data).substring(0, 200))
    return data
  } catch (error) {
    console.error('Error fetching post:', error)
    return null
  }
}

export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
  const post = await getPost(params.slug)

  if (!post) {
    return {
      title: 'Blog - AKTIV Program knjigovodstvo racunovodsvo',
      description: 'Online knjigovodstveni program za efikasno poslovanje',
    }
  }

  // Get description with proper length
  const pageDescription = post.descriptionMeta || post.excerpt || post.description?.replace(/<[^>]*>/g, '').substring(0, 160) || 'AKTIV online knjigovodstveni program'

  // Get image from files array if available
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://aktiv.rs'
  let pageImage = `${siteUrl}/images/aktiv-og-image.jpg`
  if (post.files && post.files.length > 0) {
    const defaultFile = post.files.find((f: any) => f.isDefault) || post.files[0]
    if (defaultFile && defaultFile.imagePath) {
      pageImage = `https://accountant.aktivrs.com/${defaultFile.imagePath}`
    }
  } else if (post.imageUrl) {
    pageImage = post.imageUrl
  } else if (post.imageUrls && post.imageUrls.length > 0) {
    pageImage = post.imageUrls[0]
  }

  // Ensure image URL is absolute
  const fullImage = pageImage.startsWith('http') ? pageImage : `${siteUrl}${pageImage}`

  const pageUrl = `${siteUrl}/${post.slug || post.id}/`
  const pageKeywords = post.keywords || 'računovodstvo, knjigovodstvo, AKTIV, online knjigovodstvo, digitalno računovodstvo'

  // Get author name
  const authorName = post.creator?.firstName && post.creator?.lastName
    ? `${post.creator.firstName} ${post.creator.lastName}`
    : 'AKTIV'

  // Get dates - use post dates if available, otherwise use creator dates as fallback
  const publishedDate = post.createdAt || post.publishedAt || (post.creator?.createdAt || new Date().toISOString())
  const modifiedDate = post.updatedAt || post.modifiedAt || publishedDate

  return {
    title: `${post.title} - AKTIV Program knjigovodstvo racunovodsvo`,
    description: pageDescription,
    keywords: pageKeywords,
    authors: [{ name: authorName }],
    openGraph: {
      type: 'article',
      url: pageUrl,
      title: `${post.title} - AKTIV Program knjigovodstvo racunovodsvo`,
      description: pageDescription,
      images: [
        {
          url: fullImage,
          width: 1200,
          height: 630,
          alt: post.title,
        },
      ],
      siteName: 'AKTIV Program knjigovodstvo racunovodsvo',
      locale: 'sr_RS',
      publishedTime: publishedDate,
      modifiedTime: modifiedDate,
      authors: [authorName],
    },
    twitter: {
      card: 'summary_large_image',
      title: `${post.title} - AKTIV Program knjigovodstvo racunovodsvo`,
      description: pageDescription,
      images: [fullImage],
    },
    alternates: {
      canonical: pageUrl,
    },
  }
}

export default function BlogPostPage({ params }: { params: { slug: string } }) {
  return <BlogPostPageClient slug={params.slug} />
}
