import React from 'react';
import Head from 'next/head';
import { SITE_LOGO, SITE_NAME, SITE_URL, productPath } from '../lib/seo';
import { getVariantKindLabel, isVariantAvailable, type VariantKind } from '../lib/variantStock';
import { getOfferPricing, hasValidOfferPrice, productVariantUrl } from '../lib/productOffer';

interface ProductVariant {
  id: number;
  name: string;
  volume: string;
  volumeMl: number;
  currentPrice: number;
  kind?: VariantKind;
  stock?: number;
  sku?: string;
}

interface ProductImage {
  url: string;
}

interface Product {
  id: number;
  slug: string;
  name: string;
  description: string;
  brandName: string;
  primaryImage: string;
  allImages: ProductImage[];
  stock: number;
  variants: ProductVariant[];
}

interface ProductSchemaProps {
  product: Product;
  selectedVariant?: ProductVariant;
}

const ProductSchema: React.FC<ProductSchemaProps> = ({ product, selectedVariant }) => {
  const images = [
    product.primaryImage,
    ...(product.allImages?.map((img) => img.url) || []),
  ].filter(Boolean);

  // Describe the exact offer displayed in the purchase controls, including
  // server-rendered ?variant= links. Never invent a zero-priced offer.
  const variant = selectedVariant && hasValidOfferPrice(selectedVariant) ? selectedVariant : undefined;

  const nextYear = new Date();
  nextYear.setFullYear(nextYear.getFullYear() + 1);
  const priceValidUntil = nextYear.toISOString().split('T')[0];

  const shippingDetails = {
    '@type': 'OfferShippingDetails',
    shippingRate: {
      '@type': 'MonetaryAmount',
      value: '0',
      currency: 'CZK',
    },
    shippingDestination: {
      '@type': 'DefinedRegion',
      addressCountry: 'CZ',
    },
    deliveryTime: {
      '@type': 'ShippingDeliveryTime',
      handlingTime: {
        '@type': 'QuantitativeValue',
        minValue: 0,
        maxValue: 1,
        unitCode: 'DAY',
      },
      transitTime: {
        '@type': 'QuantitativeValue',
        minValue: 1,
        maxValue: 2,
        unitCode: 'DAY',
      },
    },
  };

  const returnPolicy = {
    '@type': 'MerchantReturnPolicy',
    applicableCountry: 'CZ',
    returnPolicyCategory: 'https://schema.org/MerchantReturnFiniteReturnWindow',
    merchantReturnDays: 14,
    returnMethod: 'https://schema.org/ReturnByMail',
    returnFees: 'https://schema.org/ReturnShippingFees',
  };

  const jsonLd = {
    '@context': 'https://schema.org/',
    '@type': 'Product',
    name: product.name,
    url: productPath(product.slug),
    image: images,
    description: product.description || `Parfém ${product.name} od značky ${product.brandName}.`,
    sku: product.slug,
    brand: {
      '@type': 'Brand',
      name: product.brandName,
    },
    offers: variant ? {
      '@type': 'Offer',
      name: `${product.name} ${getVariantKindLabel(variant.kind)} ${variant.volume}`,
      sku: variant.sku || `VYS-${variant.id}`,
      url: productVariantUrl(product.slug, variant),
      ...getOfferPricing(variant),
      priceValidUntil,
      itemCondition: 'https://schema.org/NewCondition',
      availability: isVariantAvailable(variant, product.stock)
        ? 'https://schema.org/InStock'
        : 'https://schema.org/OutOfStock',
      seller: {
        '@type': 'Organization',
        name: SITE_NAME,
        url: SITE_URL,
        logo: SITE_LOGO,
      },
      shippingDetails,
      hasMerchantReturnPolicy: returnPolicy,
    } : undefined,
  };

  return (
    <Head>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c') }}
      />
      {variant && <meta property="product:price:amount" content={Number(variant.currentPrice).toFixed(2)} />}
      {variant && <meta property="product:price:currency" content="CZK" />}
    </Head>
  );
};

export default ProductSchema;
