"use client"

import { useEffect, useState } from "react"
import { notFound, useRouter } from "next/navigation"
import { Product } from "@/lib/catalog"
import { Skeleton } from "@/components/ui/skeleton"
import { fetchProduct } from "@/lib/api"
import { ImageSlider } from "@/components/product/ImageSlider"
import { ProductDetails } from "@/components/product/ProductDetails"

export default function ProductPage({ params }: { params: { slug: string } }) {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [product, setProduct] = useState<Product | null>(null)
  const router = useRouter()

  useEffect(() => {
    const loadProduct = async () => {
      setLoading(true)
      try {
        // fetchProduct возвращает объект Product напрямую, а не обертку ApiResponse
        const productData = await fetchProduct(params.slug)
        
        // Проверяем, что получены данные
        if (!productData) {
          setError("Продукт не найден")
          return
        }
        
        // Преобразуем тип API Product в тип из catalog.ts
        setProduct(productData as unknown as Product)
      } catch (err) {
        console.error("Error fetching product:", err)
        setError("Ошибка при загрузке продукта")
      } finally {
        setLoading(false)
      }
    }

    loadProduct()
  }, [params.slug])

  if (error && !loading) {
    return (
      <div className="container py-12 text-center">
        <h1 className="text-2xl font-semibold mb-4">Ошибка</h1>
        <p>{error}</p>
        <button 
          onClick={() => router.push("/catalog")}
          className="mt-4 bg-primary text-white px-4 py-2 rounded hover:bg-primary/90 transition-colors"
        >
          Вернуться в каталог
        </button>
      </div>
    )
  }

  if (loading) {
    return <ProductSkeleton />
  }

  if (!product) {
    return notFound()
  }

  return (
    <div className="container py-6 md:py-10">
      <nav className="flex flex-wrap items-center text-sm text-gray-500 mb-4 sm:mb-6 overflow-x-auto whitespace-nowrap pb-2">
        <a href="/" className="hover:text-primary">
          Главная
        </a>
        <span className="mx-2">›</span>
        <a href="/catalog" className="hover:text-primary">
          Каталог
        </a>
        {product.category && (
          <>
            <span className="mx-2">›</span>
            <a
              href={`/catalog?category_id=${product.category.id}`}
              className="hover:text-primary"
            >
              {product.category.name}
            </a>
          </>
        )}
        <span className="mx-2">›</span>
        <span className="text-primary font-medium truncate max-w-[150px] sm:max-w-xs">
          {product.name}
        </span>
      </nav>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-8 lg:gap-12">
        <div>
          <ImageSlider 
            images={product.images || []} 
            productName={product.name} 
          />
        </div>
        <div>
          <ProductDetails product={product} />
        </div>
      </div>
    </div>
  )
}

function ProductSkeleton() {
  return (
    <div className="container py-6 md:py-10">
      <div className="mb-4 sm:mb-6">
        <Skeleton className="h-6 w-2/3" />
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-8 lg:gap-12">
        <div>
          <Skeleton className="aspect-square w-full rounded-lg" />
          <div className="mt-3 flex gap-2 justify-center">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} className="w-16 h-16 rounded" />
            ))}
          </div>
        </div>
        <div className="space-y-4">
          <Skeleton className="h-10 w-4/5" />
          <Skeleton className="h-6 w-1/3" />
          <Skeleton className="h-24 w-full" />
          <div className="space-y-2">
            <Skeleton className="h-8 w-full" />
            <Skeleton className="h-8 w-full" />
          </div>
          <Skeleton className="h-12 w-full" />
          <div className="space-y-1 mt-6">
            <Skeleton className="h-4 w-full" />
            <Skeleton className="h-4 w-full" />
            <Skeleton className="h-4 w-4/5" />
          </div>
        </div>
      </div>
    </div>
  )
} 