import React, { Suspense } from "react"
import Image from "next/image"
import { notFound } from "next/navigation"
import { HttpTypes } from "@medusajs/types"

import ImageGallery from "@modules/products/components/image-gallery"
import ProductActions from "@modules/products/components/product-actions"
import ProductTabs from "@modules/products/components/product-tabs"
import RelatedProducts from "@modules/products/components/related-products"
import SkeletonRelatedProducts from "@modules/skeletons/templates/skeleton-related-products"
import LocalizedClientLink from "@modules/common/components/localized-client-link"
import ProductActionsWrapper from "./product-actions-wrapper"

const CATEGORY_COLORS: Record<string, { accent: string; light: string }> = {
  "construction": { accent: "bg-orange-400", light: "bg-orange-50" },
  "fine motor":   { accent: "bg-pink-400",   light: "bg-pink-50" },
  "movement":     { accent: "bg-sky-400",    light: "bg-sky-50" },
  "sensory":      { accent: "bg-green-400",  light: "bg-green-50" },
  "rent":         { accent: "bg-violet-400", light: "bg-violet-50" },
}

function getCategoryStyle(categoryName?: string) {
  if (!categoryName) return { accent: "bg-yellow-400", light: "bg-yellow-50" }
  const key = Object.keys(CATEGORY_COLORS).find((k) =>
    categoryName.toLowerCase().includes(k)
  )
  return key ? CATEGORY_COLORS[key] : { accent: "bg-yellow-400", light: "bg-yellow-50" }
}

type ProductTemplateProps = {
  product: HttpTypes.StoreProduct
  region: HttpTypes.StoreRegion
  countryCode: string
  images: HttpTypes.StoreProductImage[] | null
}

const ProductTemplate: React.FC<ProductTemplateProps> = ({
  product,
  region,
  countryCode,
  images,
}) => {
  if (!product || !product.id) return notFound()

  const category = product.categories?.[0]?.name
  const style = getCategoryStyle(category)

  return (
    <div className="bg-white min-h-screen" data-testid="product-container">
      {/* Category-colored top accent bar */}
      <div className={`h-1.5 w-full ${style.accent}`} />

      <div className="max-w-7xl mx-auto px-4 sm:px-6">
        {/* Breadcrumb */}
        <nav className="flex items-center gap-1.5 py-4 text-xs text-gray-400 flex-wrap">
          <LocalizedClientLink href="/" className="hover:text-gray-600 transition-colors">Home</LocalizedClientLink>
          <span>/</span>
          <LocalizedClientLink href="/store" className="hover:text-gray-600 transition-colors">Products</LocalizedClientLink>
          {category && (
            <>
              <span>/</span>
              <span className="text-gray-400">{category}</span>
            </>
          )}
          <span>/</span>
          <span className="text-gray-700 font-semibold truncate max-w-[180px]">{product.title}</span>
        </nav>

        {/* Main product section */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 lg:gap-14 pb-14">

          {/* LEFT: Image gallery */}
          <div>
            <div className={`rounded-2xl overflow-hidden border-2 border-black ${style.light}`}>
              <div className={`h-1.5 w-full ${style.accent}`} />
              <ImageGallery images={images ?? []} />
            </div>
          </div>

          {/* RIGHT: Product info + actions */}
          <div className="flex flex-col gap-5">
            {/* Category badge */}
            {category && (
              <span className={`text-[10px] font-black uppercase tracking-widest text-white ${style.accent} px-3 py-1 rounded-full w-fit`}>
                {category}
              </span>
            )}

            {/* Title */}
            <h1
              className="text-3xl md:text-4xl font-black text-black leading-tight"
              data-testid="product-title"
            >
              {product.title}
            </h1>

            <div className="border-t border-gray-100" />

            {/* Actions: price, options, add to cart */}
            <Suspense
              fallback={
                <ProductActions disabled={true} product={product} region={region} />
              }
            >
              <ProductActionsWrapper id={product.id} region={region} />
            </Suspense>

            {/* Trust badges */}
            <div className={`rounded-2xl ${style.light} border border-black/5 p-4 grid grid-cols-2 gap-3`}>
              {[
                { icon: "🚚", text: "Gratis ongkir 500k+" },
                { icon: "🔄", text: "Easy returns" },
                { icon: "🛡️", text: "Quality guaranteed" },
                { icon: "💬", text: "WhatsApp support" },
              ].map((b) => (
                <div key={b.text} className="flex items-center gap-2">
                  <span className="text-base">{b.icon}</span>
                  <span className="text-xs text-gray-600 font-medium">{b.text}</span>
                </div>
              ))}
            </div>

            {/* Product tabs */}
            <Suspense fallback={null}>
              <ProductTabs product={product} />
            </Suspense>
          </div>
        </div>
      </div>

      {/* Description — full width below the fold */}
      {product.description && (
        <div className="border-t-2 border-gray-100 py-10">
          <div className="max-w-7xl mx-auto px-4 sm:px-6">
            <div className="flex items-center gap-4 mb-6">
              <h2 className="text-xl font-black text-black">Tentang Produk Ini</h2>
              <div className={`h-1 flex-1 ${style.accent} rounded-full`} />
            </div>
            <div
              className={`rounded-2xl ${style.light} border border-black/5 p-6 md:p-8 product-description`}
              dangerouslySetInnerHTML={{ __html: product.description }}
            />
          </div>
        </div>
      )}

      {/* Related products */}
      <div className="bg-gray-50 border-t-2 border-gray-100 py-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6">
          <div className="flex items-center gap-4 mb-6">
            <h2 className="text-xl font-black text-black">You might also like</h2>
            <div className="h-1 flex-1 bg-yellow-400 rounded-full" />
          </div>
          <Suspense fallback={<SkeletonRelatedProducts />}>
            <RelatedProducts product={product} countryCode={countryCode} />
          </Suspense>
        </div>
      </div>
    </div>
  )
}

export default ProductTemplate
