import { headers } from 'next/headers';
import type { Metadata } from 'next';
import { fetchPostDetails, getMediaUrl } from '@/lib/api';
import { notFound } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { getMaxAge } from 'next/dist/server/image-optimizer';
import PostGallery from '@/components/PostGallery';
import { MapIcon, MapPin, MapPinHouseIcon } from 'lucide-react';
import { Icon } from '@iconify/react';

interface Params {
  slug: string;
}

export async function generateMetadata(props: { params: Promise<Params> }): Promise<Metadata> {
  const params = await props.params;
  const headersList = await headers();
  const host = headersList.get('host') || '';
  const domainTheme = host.includes('rollerblindbekasi.in') ? 'rollerblindbekasi.in' : 
                      host.includes('rollerblindjakarta.in') ? 'rollerblindjakarta.in' : 
                      host;
                      
  const data = await fetchPostDetails(domainTheme, params.slug);
  const proto = headersList.get('x-forwarded-proto') || 'https'
  const uri = `/post/${params.slug}`

  if (!data || !data.post) {
    return {
      title: 'Post Not Found',
    };
  }

  return {
    title: data.post.meta_title || `${data.post.title} | ${data.domain?.name || 'Blog'}`,
    description: data.post.meta_description || data.post.description?.replace(/<[^>]*>?/gm, '').substring(0, 160),
    keywords: data.post.meta_keyword,
    openGraph: {
       title: data.post.meta_title || data.post.title,
       description: data.post.meta_description || data.post.description?.replace(/<[^>]*>?/gm, '').substring(0, 160),
       images: data.post.media ? [getMediaUrl(data.post.media)] : [],
       type: 'article',
    },
    twitter: {
      card: 'summary_large_image',
      title: data.post.meta_title || data.post.title,
      description: data.post.meta_description || data.post.description?.replace(/<[^>]*>?/gm, '').substring(0, 160),
      images: data.post.media ? [getMediaUrl(data.post.media)] : [],
    },
    alternates: {
      canonical: `${proto}://${host}${uri}`,
    },
  };
}

export default async function PostPage(props: { params: Promise<Params> }) {
  const params = await props.params;
  const headersList = await headers();
  const host = headersList.get('host') || '';
  const domainTheme = host.includes('rollerblindbekasi.in') ? 'rollerblindbekasi.in' : 
                      host.includes('rollerblindjakarta.in') ? 'rollerblindjakarta.in' : 
                      host;

  const data = await fetchPostDetails(domainTheme, params.slug);

  if (!data || !data.post) {
    notFound();
  }

  const { post } = data;
  
  return (
    <article className="container mx-auto px-4 py-16 md:py-24 max-w-4xl">
      <div className="mb-4 text-sm font-medium text-primary">
         {
          post.category?.code === '2' || post.category === '2' ?
          <Link href="/pemasangan" className="hover:underline">← Kembali ke pemasangan</Link>
          :  
          <Link href="/post-list" className="hover:underline">← Kembali ke semua artikel</Link>
         }
      </div>

      <header className="mb-10 text-center sm:text-left">
         {post.category && (
             <span className="inline-block px-3 py-1 mb-4 text-xs font-semibold tracking-wider text-primary bg-primary/10 rounded-full uppercase">
                 {post.category?.value || post.category}
             </span>
         )}
        <h1 className="text-4xl font-extrabold tracking-tight lg:text-5xl mb-6">
          {post.title}
        </h1>
        
        {/* Pemasangan Info Block */}
        {(post.category?.code === '2' || post.category === '2') && (
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between text-sm font-medium text-muted-foreground border-b pb-4 mb-6 gap-4">
            <div className="flex items-center">
              <Icon icon="mdi:map-marker" className="w-4 h-4 text-red-500 mr-1 flex-shrink-0" />
              <span>{post.province?.name || '-'}, {post.city?.name || '-'}</span>
            </div>
            {post.installation_date && (
              <div className="flex items-center">
                <span>{new Date(post.installation_date).toLocaleDateString('id-ID', { year: 'numeric', month: 'long', day: 'numeric' })}</span>
              </div>
            )}
          </div>
        )}
      </header>

      {/* Pemasangan Specs Block */}
      {(post.category?.code === '2' || post.category === '2') && (
        <div className="bg-muted rounded-xl p-6 mb-10 border grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="flex flex-col">
            <div className="flex items-center text-sm font-semibold text-muted-foreground mb-2">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src="https://api.iconify.design/mdi/tag-outline.svg" alt="Produk" className="w-4 h-4 mr-2" />
              PRODUK
            </div>
            <p className="font-medium text-foreground">{post.product?.name || '-'}</p>
          </div>
          <div className="flex flex-col">
            <div className="flex items-center text-sm font-semibold text-muted-foreground mb-2">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src="https://api.iconify.design/mdi/tag-outline.svg" alt="Material" className="w-4 h-4 mr-2" />
              MATERIAL
            </div>
            <p className="font-medium text-foreground">{post.material_name || '-'}</p>
          </div>
          <div className="flex flex-col">
            <div className="flex items-center text-sm font-semibold text-muted-foreground mb-2">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src="https://api.iconify.design/mdi/tag-outline.svg" alt="Jumlah" className="w-4 h-4 mr-2" />
              JUMLAH
            </div>
            <p className="font-medium text-foreground">{post.quantity || '-'}</p>
          </div>
        </div>
      )}

      {/* Regular Hero Thumbnail (Hidden for Pemasangan) */}
      {!(post.category?.code === '2' || post.category === '2') && (
        <div className="w-full aspect-video bg-muted rounded-xl mb-10 border flex items-center justify-center overflow-hidden">
            {
              post.media ? 
                <div className="aspect-video w-full overflow-hidden">
                <Image
                  src={getMediaUrl(post.media)}
                  alt={post.title}
                  width={600}
                  height={400}
                  className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                />
              </div>
              :
              <div className="text-primary/20 font-serif text-6xl md:text-8xl select-none px-4 text-center text-balance">
                {post.title}
              </div>
            }
        </div>
      )}

      <div 
        className="prose prose-lg dark:prose-invert max-w-none 
          prose-headings:font-bold prose-a:text-primary hover:prose-a:underline"
        dangerouslySetInnerHTML={{ __html: post.description }}
      />
      
      {post.post_media && post.post_media.length > 0 && (
        <PostGallery media={post.post_media} />
      )}

      <hr className="my-12 border-muted" />
      
      <div className="flex justify-between items-center">
         <p className="text-muted-foreground text-sm">Terima kasih telah membaca</p>
         {
          post.category?.code === '2' || post.category === '2' ?
          <Link href="/pemasangan" className="inline-flex h-10 items-center justify-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90">
             Lihat pemasangan lainnya
          </Link>
          :  
          <Link href="/post-list" className="inline-flex h-10 items-center justify-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90">
             Lihat artikel lainnya
          </Link>
         }
      </div>
    </article>
  );
}
