export type Product = {
    id: string;
    name: string;
    price: string;
    imageSrc: string;
    imageAlt?: string;
    brand?: string;
    variant?: string;
    rating?: number;
    reviewCount?: string;
    onFavorite?: () => void;
    onProductClick?: () => void;
    isFavorited?: boolean;
};

export const defaultProducts: Product[] = [
    {
        id: "1",
        name: "Classic White Sneakers",
        price: "$129",
        brand: "Nike",
        variant: "White / Size 42",
        rating: 4.5,
        reviewCount: "128",
        imageSrc: "/placeholders/placeholder3.avif",
        imageAlt: "Classic white sneakers",
    },
    {
        id: "2",
        name: "Leather Crossbody Bag",
        price: "$89",
        brand: "Coach",
        variant: "Brown / Medium",
        rating: 4.8,
        reviewCount: "256",
        imageSrc: "/placeholders/placeholder4.webp",
        imageAlt: "Brown leather crossbody bag",
    },
    {
        id: "3",
        name: "Wireless Headphones",
        price: "$199",
        brand: "Sony",
        variant: "Black",
        rating: 4.7,
        reviewCount: "512",
        imageSrc: "/placeholders/placeholder3.avif",
        imageAlt: "Black wireless headphones",
    },
    {
        id: "4",
        name: "Minimalist Watch",
        price: "$249",
        brand: "Fossil",
        variant: "Silver / 40mm",
        rating: 4.6,
        reviewCount: "89",
        imageSrc: "/placeholders/placeholder4.webp",
        imageAlt: "Silver minimalist watch",
    },
];

function formatPrice(amount: number, currency: string): string {
    const formatter = new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: currency.toUpperCase(),
        minimumFractionDigits: 0,
        maximumFractionDigits: 2,
    });
    return formatter.format(amount / 100);
}

export async function fetchProducts(): Promise<Product[]> {
    const apiUrl = process.env.NEXT_PUBLIC_API_URL;
    const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;

    if (!apiUrl || !projectId) {
        console.warn("NEXT_PUBLIC_API_URL or NEXT_PUBLIC_PROJECT_ID not configured");
        return [];
    }

    try {
        const url = `${apiUrl}/stripe/project/products?projectId=${projectId}`;
        const response = await fetch(url, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        });

        if (!response.ok) {
            console.warn(`API request failed with status ${response.status}`);
            return [];
        }

        const resp = await response.json();
        const data = resp.data || resp;

        if (!Array.isArray(data) || data.length === 0) {
            return [];
        }

        return data.map((product: any) => ({
            id: product.id || String(Math.random()),
            name: product.name || "Untitled Product",
            price: product.default_price?.unit_amount
                ? formatPrice(product.default_price.unit_amount, product.default_price.currency || "usd")
                : product.price || "$0",
            imageSrc: product.images?.[0] || product.imageSrc || "/placeholders/placeholder3.avif",
            imageAlt: product.imageAlt || product.name || "",
            brand: product.metadata?.brand || product.brand || "",
            variant: product.metadata?.variant || product.variant || "",
            rating: product.metadata?.rating ? parseFloat(product.metadata.rating) : undefined,
            reviewCount: product.metadata?.reviewCount || undefined,
        }));
    } catch (error) {
        console.error("Error fetching products:", error);
        return [];
    }
}
