import React, { useState } from "react";
import Card from "./Card";
import AssetPreview from "./AssetPreview";
import { fetchGltfUrl } from "../../services/marketplace/fetchGltfUrl";

interface ModelData {
  CreatedBy: string;
  animated: string | null;
  category: string;
  description: string;
  filename: string;
  isArchieve: boolean;
  assetId: string;
  tags: string;
  thumbnail: string;
  uploadDate: number;
  _id: string;
  price: number;
  AssetID: string;
}
interface ModelsProps {
  models: ModelData[];
}

const CardsContainer: React.FC<ModelsProps> = ({ models }) => {
  const [modelUrl, setModelUrl] = useState<string>("");
  const [selectedCard, setSelectedCard] = useState<{
    assetName: string;
    uploadedOn: number;
    price: number;
    rating: number;
    views: number;
    description: string;
    AssetID: string;
  } | null>(null);

  const handleCardSelect = async (cardData: {
    assetName: string;
    uploadedOn: number;
    price: number;
    rating: number;
    views: number;
    description: string;
    AssetID: string;
  }) => {
    setSelectedCard(cardData);
    const res = await fetchGltfUrl(cardData.assetName, cardData.AssetID);
    // console.log("res: ", res);
    setModelUrl(res.url);
  };
  return (
    <div className="cards-container-wrapper">
      <div className="cards-container-container">
        <div className="header">Products You May Like</div>
        <div className="cards-wrapper-container">
          {models.length > 0 &&
            models.map((assetDetail) => (
              <React.Fragment key={assetDetail._id}>
                <Card
                  assetName={assetDetail?.filename}
                  uploadedOn={assetDetail.uploadDate}
                  price={assetDetail?.price}
                  rating={4.5}
                  views={800}
                  onSelectCard={handleCardSelect}
                  AssetID={assetDetail.AssetID}
                  image={assetDetail.thumbnail}
                  modelUrl={assetDetail.assetId}
                  description={assetDetail.description}
                />
              </React.Fragment>
            ))}
          {/* <RenderOverlay> */}
          {selectedCard && (
            <AssetPreview
              selectedCard={selectedCard}
              setSelectedCard={setSelectedCard}
              modelUrl={modelUrl}
            />
          )}
          {/* </RenderOverlay> */}
        </div>
      </div>
    </div>
  );
};

export default CardsContainer;
