import Image from "next/image";

interface ProductItem {
    id?: number;
    image?: string | string[];
    is_default_image?: boolean;
    reg_price?: number;
    sale_price?: number;
    attributes?: Array<{ type: string; value?: { label?: string; hex?: string } }>;
}

const formatPrice = (n: number) =>
    new Intl.NumberFormat("id-ID", { style: "decimal", minimumFractionDigits: 0 }).format(n);

const LayoutPreview = ({
    images,
    productItems = [],
    productRegPrice = 0,
    productSalePrice = 0,
    productSoldCount = 0,
    productTitle = '',
}: {
    images: string[];
    productItems?: ProductItem[];
    productRegPrice?: number;
    productSalePrice?: number;
    productSoldCount?: number;
    productTitle?: string;
}) => {
    const defaultItem = productItems.find((i) => i.is_default_image);
    const previewImageSrc = defaultItem?.image
        ? Array.isArray(defaultItem.image)
            ? defaultItem.image[0]
            : defaultItem.image
        : images[0];

    const variationColors = productItems
        .map((item) => {
            const colorAttr = item.attributes?.find((a) => a.type === "color");
            if (!colorAttr || !colorAttr.value) return null;

            const value = colorAttr.value;
            const label =
                typeof value === "object" && value != null && "label" in value
                    ? String((value as { label?: string }).label ?? "")
                    : "";
            const hex =
                typeof value === "object" && value != null && "hex" in value
                    ? String((value as { hex?: string }).hex ?? "")
                    : "";

            if (!label || !hex) return null;

            return { label, hex, isDefault: item.is_default_image === true };
        })
        .filter((c): c is { label: string; hex: string; isDefault: boolean } => !!c);

    const hasVariationColors = variationColors.length > 0;
    const rawColors = hasVariationColors ? variationColors : [];
    const displayColors = [...rawColors].sort((a, b) =>
        (b.isDefault ? 1 : 0) - (a.isDefault ? 1 : 0)
    );

    const displayColorsUnique = displayColors.filter(
        (c, idx, arr) => arr.findIndex((x) => x.hex === c.hex) === idx
    );

    const regPrice = defaultItem?.reg_price ?? productRegPrice;
    const salePrice = defaultItem?.sale_price ?? productSalePrice;

    return (
        <>
            <p className="text-lg">Example Layout Preview:</p>
            <div className="flex justify-between mt-4">
                <div className="relative bg-white rounded-xl shadow p-4 w-[330px] min-h-[480px] max-w-full flex flex-col gap-2 border border-gray-100">
                    <div className=" rounded-lg overflow-hidden h-full flex items-center justify-center bg-gray-50 border border-gray-200 shadow-sm">
                        {previewImageSrc ? (
                            <Image
                                src={previewImageSrc}
                                alt="Product"
                                className="object-contain h-full w-auto max-w-full"
                                width={330}
                                height={480}
                            />
                        ) : (
                            <span className="text-gray-400 text-xs">No image</span>
                        )}
                    </div>
                    <div className="flex items-center justify-between mt-1 gap-1">
                        <div className="text-base font-semibold text-gray-800 truncate">
                            {productTitle}
                        </div>
                        <button type="button" className="text-[#704e80] flex-shrink-0">
                            <svg
                                width="20"
                                height="20"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="1.7"
                                viewBox="0 0 24 24"
                                className="inline align-middle"
                            >
                                <path
                                    d="M12.36 20.448c-.235.172-.61.172-.845 0-4.006-2.937-6.902-5.884-6.902-8.976C4.613 8.362 6.795 6.5 9.278 6.5c1.064 0 2.112.398 2.902 1.092A4.232 4.232 0 0 1 15.082 6.5c2.483 0 4.665 1.862 4.665 4.972 0 3.092-2.896 6.039-6.902 8.976Z"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                />
                            </svg>
                        </button>
                    </div>
                    <div className="flex items-center gap-2 text-sm mt-1">
                        {regPrice > 0 && (
                            <span className="line-through text-gray-400 font-normal">
                                Rp {formatPrice(regPrice)}
                            </span>
                        )}
                        <span className="font-bold text-[#704e80]">
                            Rp {formatPrice(salePrice > 0 ? salePrice : regPrice)}
                        </span>
                    </div>

                    <div className="flex items-center justify-between mt-auto">
                        <div className="text-sm text-gray-500">Terjual {productSoldCount}</div>
                        {productItems &&
                            productItems.length > 0 &&
                            displayColorsUnique.length > 0 && (
                                <div className="flex gap-2 mt-1 mb-2">
                                    {displayColorsUnique.map((c, idx) => (
                                        <span
                                            key={idx}
                                            className="h-5 w-5 rounded-full border-2 border-white shadow"
                                            style={{
                                                background: c.hex,
                                                boxShadow: c.isDefault
                                                    ? "0 0 0 1.5px #704e80"
                                                    : "0 0 0 1px #ccc",
                                            }}
                                            title={c.label}
                                        />
                                    ))}
                                </div>
                            )}
                    </div>
                </div>
            </div>
        </>
    );
};

export default LayoutPreview;