import { useMemo, useState } from "react";
import { toast } from "sonner";
import { effects } from "../constants/effects";
import { getFrameConfig } from "../constants/frameConfig";
import { getPreviewImgSrc } from "../utils/imageHelpers";

type ProductFramedImagePreviewProps = {
    uploadedImage: any;
    imageIndex: number;
    frames: any[];
    selectedFrame: number | null;
    selectedEffect: string;
    isUploading: boolean;
    openCropModal: (img: any) => void;
};

function getContainedSize(params: {
    originalWidth: number;
    originalHeight: number;
    availableWidth: number;
    availableHeight: number;
}) {
    const {
        originalWidth,
        originalHeight,
        availableWidth,
        availableHeight,
    } = params;

    if (!originalWidth || !originalHeight || !availableWidth || !availableHeight) {
        return {
            width: availableWidth,
            height: "auto" as const,
        };
    }

    const imageRatio = originalWidth / originalHeight;
    const availableRatio = availableWidth / availableHeight;

    // مثل Cropper: نقرر هل الصورة محكومة بالعرض أو بالارتفاع
    if (availableRatio > imageRatio) {
        // المساحة أعرض من الصورة، إذًا الارتفاع هو المحدد
        return {
            width: availableHeight * imageRatio,
            height: availableHeight,
        };
    }

    // الصورة محكومة بالعرض
    return {
        width: availableWidth,
        height: availableWidth / imageRatio,
    };
}

export default function ProductFramedImagePreview({
                                                      uploadedImage,
                                                      imageIndex,
                                                      frames,
                                                      selectedFrame,
                                                      selectedEffect,
                                                      isUploading,
                                                      openCropModal,
                                                  }: ProductFramedImagePreviewProps) {
    const [loadedSize, setLoadedSize] = useState<{
        width: number;
        height: number;
    } | null>(null);

    if (!selectedFrame) return null;

    const frame = frames.find((f) => Number(f.id) === Number(selectedFrame));
    const cfg = getFrameConfig(Number(selectedFrame));

    const originalWidth =
        Number(uploadedImage?.width) ||
        Number(uploadedImage?.original_width) ||
        loadedSize?.width ||
        0;

    const originalHeight =
        Number(uploadedImage?.height) ||
        Number(uploadedImage?.original_height) ||
        loadedSize?.height ||
        0;

    const imageSize = useMemo(() => {
        const availableWidth = cfg.boxSize - cfg.imageSubtract;

        // حسب تصميمك الحالي عندك marginTop، لذلك نطرحها من الارتفاع المتاح
        const availableHeight = cfg.boxSize - cfg.marginTop;

        return getContainedSize({
            originalWidth,
            originalHeight,
            availableWidth,
            availableHeight,
        });
    }, [
        cfg.boxSize,
        cfg.imageSubtract,
        cfg.marginTop,
        originalWidth,
        originalHeight,
    ]);

    return (
        <div
            className="relative cursor-pointer"
            style={{
                width: `${cfg.boxSize}px`,
                minHeight: `${cfg.previewMinHeight}px`,
                flexShrink: 0,
            }}
        >
            <div
                style={{
                    width: `${cfg.boxSize}px`,
                    height: `${cfg.boxSize}px`,
                    overflow: "hidden",
                    position: "relative",
                    backgroundImage: `url(${frame?.image})`,
                    backgroundSize: `${cfg.bgSize}px ${cfg.bgSize}px`,
                    backgroundRepeat: "no-repeat",
                    backgroundPosition: "0 0",
                    border: "none",
                    padding: 0,
                }}
            >
                <img
                    onLoad={(e) => {
                        const img = e.currentTarget;

                        if (!loadedSize) {
                            setLoadedSize({
                                width: img.naturalWidth,
                                height: img.naturalHeight,
                            });
                        }
                    }}
                    onClick={() => {
                        if (isUploading) {
                            toast.info("يرجى الانتظار حتى اكتمال رفع الصورة");
                            return;
                        }

                        openCropModal({
                            ...uploadedImage,

                            // مهم: نمرر قياس العرض المعروض مثل cropper-canvas
                            preview_canvas_width: imageSize.width,
                            preview_canvas_height:
                                imageSize.height === "auto" ? null : imageSize.height,

                            original_width: originalWidth,
                            original_height: originalHeight,
                        });
                    }}
                    src={`${getPreviewImgSrc(uploadedImage)}?t=${
                        uploadedImage?.updated_at || Date.now()
                    }`}
                    alt={`image-${imageIndex}`}
                    style={{
                        display: "block",

                        // بدل maxWidth فقط، نضع القياس المحسوب
                        width:
                            typeof imageSize.width === "number"
                                ? `${imageSize.width}px`
                                : imageSize.width,

                        height:
                            typeof imageSize.height === "number"
                                ? `${imageSize.height}px`
                                : imageSize.height,

                        margin: `${cfg.marginTop}px auto 0 ${cfg.marginLeft}px`,
                        filter: effects[selectedEffect as keyof typeof effects],
                    }}
                />
            </div>
        </div>
    );
}