"use client";

import { Features, RightSide, SliderComp } from "@/components/pages/products";
import { useProductPageInfo } from "@/store/useProduct";
import { useQuery } from "@tanstack/react-query";
import httpClient from "@/request/api";
import { endPoints } from "@/request/links";
import { AlertCircle } from "lucide-react";
import { LoadingSkeleton } from "@/components/pages/products/slug/loading";
import { EmptyState } from "@/components/pages/products/slug/empty";
import { useEffect } from "react";

// Types
interface ProductImage {
  id: number;
  product: number;
  image: string;
  is_main: boolean;
  order: number;
}

interface ProductDetail {
  id: number;
  name: string;
  articular: string;
  status: string;
  description: string;
  size: number;
  price: string;
  features: string[];
  images: ProductImage[];
}

export default function SlugPage() {
  const productZustand = useProductPageInfo((state) => state.product);

  const { data: product, isLoading } = useQuery({
    queryKey: ["product", productZustand.id],
    queryFn: () => httpClient(endPoints.product.detail(productZustand.id)),
    select: (data) => data?.data?.data as ProductDetail,
    enabled: !!productZustand.id,
  });

  useEffect(()=>console.log("product detail: ",product))

  // Loading State
  if (isLoading) {
    return <LoadingSkeleton />;
  }

  // Empty State
  if (!product) {
    return <EmptyState />;
  }

  // Extract images
  const productImages = product.images?.map((img) => img.image) || [];
  const mainImage = product.images?.find((img) => img.is_main)?.image || productImages[0] || "";
  const features = product.features.map((item:any)=>item.name)

  return (
    <div className="min-h-screen bg-[#1e1d1c] py-32 lg:py-40 px-4 md:px-8">
      <div className="max-w-7xl mx-auto">
        {/* Main Product Section */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12 mb-12">
          {/* Left - Image Slider */}
          <SliderComp imgs={productImages} />

          {/* Right - Product Info */}
          <RightSide
            id={product.id}
            title={product.name}
            articular={product.articular}
            status={product.status}
            description={product.description}
            price={product.price}
            image={mainImage}
          />
        </div>

        {/* Features Section */}
        {product.features && product.features.length > 0 && (
          <Features features={features} />
        )}
      </div>
    </div>
  );
}
