import { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { getProductBySlug, getAllProducts, getCategoriesByLocale } from '@/lib/data';
import { getSiteInfo, t, getLocaleFromPath, getLocalizedPath } from '@/lib/i18n';
import { SEO } from '@/components/SEO';
import { LocaleSwitcher } from '@/components/LocaleSwitcher';
import { ContentRenderer } from '@/components/content/ContentRenderer';

interface PageProps {
  params: {
    slug: string;
    locale?: string;
  };
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const locale = (params.locale as string) || 'en';
  const product = getProductBySlug(params.slug, locale as 'en' | 'de');
  
  if (!product) {
    return {
      title: 'Product not found',
    };
  }

  const site = getSiteInfo();
  
  return {
    title: `${product.name} | ${site.title}`,
    description: product.shortDescriptionHtml || product.descriptionHtml.substring(0, 160) || '',
    alternates: {
      canonical: getLocalizedPath(`/product/${product.slug}`, locale as 'en' | 'de'),
      languages: {
        'en': `/en/product/${product.slug}`,
        'de': `/de/product/${product.slug}`,
      },
    },
    openGraph: {
      title: product.name,
      description: product.shortDescriptionHtml || product.descriptionHtml.substring(0, 160) || '',
      type: 'website',
      locale,
      ...(product.images && product.images.length > 0 && {
        images: product.images.map(img => ({ url: img, alt: product.name })),
      }),
    },
  };
}

export async function generateStaticParams() {
  const productsEN = getAllProducts();
  const productsDE = getAllProducts();
  
  const enParams = productsEN.filter(p => p.locale === 'en').map((product) => ({
    slug: product.slug,
    locale: 'en',
  }));
  
  const deParams = productsDE.filter(p => p.locale === 'de').map((product) => ({
    slug: product.slug,
    locale: 'de',
  }));
  
  return [...enParams, ...deParams];
}

export default async function ProductDetailPage({ params }: PageProps) {
  const locale = (params.locale as string) || 'en';
  const product = getProductBySlug(params.slug, locale as 'en' | 'de');
  
  if (!product) {
    notFound();
  }

  // Content is already processed during data export
  const processedDescription = product.descriptionHtml || '';
  const processedShortDescription = product.shortDescriptionHtml || '';

  // Get related products (same category)
  const allProducts = getAllProducts();
  const relatedProducts = allProducts
    .filter((p: any) =>
      p.locale === locale &&
      p.slug !== product.slug &&
      p.categories?.some((cat: any) => product.categories?.some((pc: any) => pc.slug === cat.slug))
    )
    .slice(0, 4);

  return (
    <>
      <SEO
        title={product.name}
        description={product.shortDescriptionHtml || product.descriptionHtml.substring(0, 160) || ''}
        locale={locale as 'en' | 'de'}
        path={`/product/${product.slug}`}
        type="product"
        images={product.images}
      />
        
      <div className="bg-white py-12 sm:py-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Back to products link */}
          <div className="mb-8">
            <Link
              href={getLocalizedPath('/products', locale as 'en' | 'de')}
              className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900 transition-colors"
            >
              <svg className="mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
              {t('products.backToProducts', locale as 'en' | 'de')}
            </Link>
          </div>

          <div className="lg:grid lg:grid-cols-2 lg:gap-x-12 lg:items-start">
            {/* Product Images */}
            <div className="flex flex-col-reverse">
              {product.images && product.images.length > 0 ? (
                <>
                  <div className="hidden lg:grid lg:grid-cols-1 lg:gap-4 mt-4">
                    {product.images.map((img: string, index: number) => (
                      <div key={index} className="aspect-square overflow-hidden rounded-lg bg-gray-100">
                        <img
                          src={img}
                          alt={`${product.name} - ${index + 1}`}
                          className="h-full w-full object-cover object-center"
                          loading={index === 0 ? 'eager' : 'lazy'}
                        />
                      </div>
                    ))}
                  </div>
                  <div className="lg:hidden aspect-square overflow-hidden rounded-lg bg-gray-100 mb-4">
                    <img
                      src={product.images[0]}
                      alt={product.name}
                      className="h-full w-full object-cover object-center"
                      loading="eager"
                    />
                  </div>
                </>
              ) : (
                <div className="aspect-square overflow-hidden rounded-lg bg-gray-100 flex items-center justify-center">
                  <svg className="h-24 w-24 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                </div>
              )}
            </div>

            {/* Product Info */}
            <div className="mt-10 px-4 sm:px-0 sm:mt-16 lg:mt-0">
              {/* Categories */}
              {product.categories && product.categories.length > 0 && (
                <div className="flex flex-wrap gap-2 mb-4">
                  {product.categories.map((cat: any) => (
                    <Link
                      key={cat.slug}
                      href={getLocalizedPath(`/product-category/${cat.slug}`, locale as 'en' | 'de')}
                      className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 hover:bg-blue-100 transition-colors"
                    >
                      {cat.name}
                    </Link>
                  ))}
                </div>
              )}

              <h1 className="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl mb-4">
                {product.name}
              </h1>

              {product.sku && (
                <p className="text-sm text-gray-500 mb-4">
                  {t('products.sku', locale as 'en' | 'de')}: {product.sku}
                </p>
              )}

              {processedShortDescription && (
                <div className="text-lg text-gray-600 mb-6">
                  <ContentRenderer
                    content={processedShortDescription}
                    className="text-lg text-gray-600"
                  />
                </div>
              )}

              {/* Product Description */}
              {processedDescription && (
                <div className="border-t border-gray-200 pt-6 mb-8">
                  <h3 className="text-sm font-medium text-gray-900 mb-3">
                    {t('products.description', locale as 'en' | 'de')}
                  </h3>
                  <ContentRenderer
                    content={processedDescription}
                    className="prose prose-sm max-w-none text-gray-600"
                  />
                </div>
              )}

              {/* Actions */}
              <div className="border-t border-gray-200 pt-6">
                <div className="flex flex-col sm:flex-row gap-4">
                  <Link
                    href={getLocalizedPath('/contact', locale as 'en' | 'de')}
                    className="flex-1 inline-flex justify-center items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 transition-colors shadow-sm"
                  >
                    {t('products.inquire', locale as 'en' | 'de')}
                    <svg className="ml-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                    </svg>
                  </Link>
                  <Link
                    href={getLocalizedPath('/products', locale as 'en' | 'de')}
                    className="flex-1 inline-flex justify-center items-center px-6 py-3 border border-gray-300 text-base font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 transition-colors"
                  >
                    {t('products.backToProducts', locale as 'en' | 'de')}
                  </Link>
                </div>
              </div>
            </div>
          </div>

          {/* Related Products */}
          {relatedProducts.length > 0 && (
            <div className="mt-20 border-t border-gray-200 pt-12">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">
                {t('products.relatedProducts', locale as 'en' | 'de')}
              </h2>
              <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
                {relatedProducts.map((relatedProduct: any) => (
                  <Link
                    key={relatedProduct.slug}
                    href={getLocalizedPath(`/product/${relatedProduct.slug}`, locale as 'en' | 'de')}
                    className="group block bg-white rounded-lg border border-gray-200 overflow-hidden hover:shadow-md transition-all"
                  >
                    {relatedProduct.images && relatedProduct.images.length > 0 ? (
                      <div className="aspect-square bg-gray-100 overflow-hidden">
                        <img
                          src={relatedProduct.images[0]}
                          alt={relatedProduct.name}
                          className="h-full w-full object-cover group-hover:scale-105 transition-transform duration-200"
                          loading="lazy"
                        />
                      </div>
                    ) : (
                      <div className="aspect-square bg-gray-100 flex items-center justify-center">
                        <svg className="h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                        </svg>
                      </div>
                    )}
                    <div className="p-4">
                      <h3 className="font-semibold text-gray-900 group-hover:text-blue-600 transition-colors mb-1 line-clamp-2">
                        {relatedProduct.name}
                      </h3>
                      {relatedProduct.shortDescriptionHtml && (
                        <div className="text-sm text-gray-600 line-clamp-2 mb-2">
                          <ContentRenderer
                            content={relatedProduct.shortDescriptionHtml}
                            className="text-sm text-gray-600"
                          />
                        </div>
                      )}
                      <span className="text-xs text-blue-600 font-medium">
                        {t('products.viewDetails', locale as 'en' | 'de')} →
                      </span>
                    </div>
                  </Link>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Locale Switcher */}
      <div className="bg-gray-50 py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <LocaleSwitcher />
        </div>
      </div>
    </>
  );
}