/** @format */

import placeholderImage from "@/assets/images/placeholder-image.png";
import { SERVER_URL } from "@/configs";
import React, { useCallback, useState } from "react";
import { Image, ImageSourcePropType, Platform } from "react-native";

interface Props {
    src?: string | ImageSourcePropType;
    alt?: string;
    width?: number;
    height?: number;
    is_private?: boolean;
    user?: { name?: string; full_name?: string };
    style?: object;
    priority?: boolean;
    withSkeleton?: boolean;
    isLocalImage?: boolean;
    className?: string;
}

export default function ImageLoader({ src, className, width, height, style }: Readonly<Props>) {
    const [imageError, setImageError] = useState(false);

    const getImageSource = useCallback(() => {
        if (imageError) {
            return placeholderImage;
        }

        if (typeof src === "string") {
            let imageUrl: string;

            if (src.startsWith("http")) {
                const normalised = src
                    .split("/")
                    .map((seg) => encodeURIComponent(decodeURIComponent(seg)))
                    .join("/");
                imageUrl = normalised;
            } else {
                const path = src.startsWith("/") ? src : `/${src}`;
                imageUrl = `${SERVER_URL}${path}`;
            }

            if (Platform.OS === "android") {
                imageUrl = imageUrl
                    .replace("127.0.0.1", "10.0.2.2")
                    .replace("localhost", "10.0.2.2");
            }

            return { uri: imageUrl };
        }

        return src;
    }, [src, imageError]);

    return (
        <Image
            source={getImageSource()}
            className={className}
            style={[width && height ? { width, height } : undefined, style]}
            resizeMode="cover"
            onError={() => setImageError(true)}
        />
    );
}
