import { createClient } from "@/lib/supabase-server"
import { getSiteContents } from "@/lib/data"
import { notFound } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Phone } from "lucide-react"
import { ProductGallery } from "@/components/product/product-gallery"

async function getProduct(id: string) {
    const supabase = createClient()

    // Fetch product
    const { data: product, error } = await supabase
        .from("products")
        .select("*")
        .eq("id", id)
        .eq("is_active", true)
        .single()

    if (error || !product) {
        return null
    }

    // Fetch images
    const { data: images } = await supabase
        .from("product_images")
        .select("*")
        .eq("product_id", id)
        .order("display_order", { ascending: true })

    return { ...product, images: images || [] }
}

export default async function ProductPage({ params }: { params: { id: string } }) {
    const product = await getProduct(params.id)
    const siteSettings = await getSiteContents()
    const whatsappPhone = siteSettings.contact_phone ? siteSettings.contact_phone.replace(/\s+/g, '') : "905555555555"

    if (!product) {
        notFound()
    }

    // Combine main image and gallery images for a full list, filtering duplicates if necessary
    // Logic: If gallery images exist, use them. If not, fallback to product.image_url.
    // If product.image_url is in product_images, we might duplicate, but let's just use all distinct.

    let allImages: string[] = []
    if (product.images && product.images.length > 0) {
        allImages = product.images.map((img: { image_url: string }) => img.image_url)
    } else if (product.image_url) {
        allImages = [product.image_url]
    }

    return (
        <div className="container py-12 md:py-24">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
                {/* Image Gallery Section */}
                <ProductGallery images={allImages} productName={product.name} />

                {/* Product Info Section */}
                <div className="space-y-8">
                    <div>
                        <div className="flex items-center gap-4 mb-2">
                            <Badge variant="secondary" className="text-sm uppercase tracking-wider">
                                {product.category}
                            </Badge>
                            {product.product_code && (
                                <span className="text-sm font-semibold text-slate-500">
                                    Kod: {product.product_code}
                                </span>
                            )}
                        </div>
                        <h1 className="text-4xl font-bold tracking-tight text-primary font-outfit mb-4">
                            {product.name}
                        </h1>
                        {/* NO PRICE DISPLAY as requested */}
                    </div>

                    <div className="prose prose-slate dark:prose-invert max-w-none">
                        <h3 className="text-lg font-semibold mb-2">Ürün Açıklaması</h3>
                        <p className="text-slate-600 dark:text-slate-300 leading-relaxed whitespace-pre-line">
                            {product.description || "Bu ürün için henüz detaylı açıklama eklenmemiştir."}
                        </p>
                    </div>

                    <div className="pt-6 border-t">
                        <div className="flex flex-col sm:flex-row gap-4">
                            <Button size="lg" className="w-full sm:w-auto" asChild>
                                <Link href={`https://wa.me/${whatsappPhone}?text=Merhaba, ${product.name} (Kod: ${product.product_code || "Yok"}) hakkında bilgi almak istiyorum.`} target="_blank">
                                    <Phone className="mr-2 h-5 w-5" />
                                    WhatsApp ile Fiyat Sor
                                </Link>
                            </Button>
                        </div>
                        <p className="mt-4 text-sm text-slate-500">
                            * Bu ürün hakkında detaylı bilgi ve fiyat teklifi almak için bizimle iletişime geçebilirsiniz.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    )
}
