"use client";
import { useEffect, useState } from "react";
import classNames from "classnames";
import style from "./ImagePicker.module.css";
import { useAlert } from "@core/Store/Alert.Store";

export type ImagePickerBorder = "solid" | "none";

export interface ImagePickerProps {
    name?: string;
    src: string;
    alt: string;
    border?: ImagePickerBorder;
    style?: React.CSSProperties;
    readOnly?: boolean;
    mbLimit?: number;
    imageSizeSrc?: string;
    onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
}
export default function ImagePicker(props: ImagePickerProps): React.ReactElement {
    const { readOnly = true, border = "solid", mbLimit = 1, imageSizeSrc = "" } = props;
    const [imageUrl, setImageUrl] = useState(props.src);
    const alert = useAlert();

    const getClassNames = () => {
        return classNames(
            style.imagePickerContainer,
            border === "none" ? style.avatarBorderNone : style.avatarBorderSolid
        );
    };

    const isImageUrl = (url: string): boolean => {
        const extensionValidation = url.match(/\.(jpeg|jpg|gif|png|webp|)$/) != null;

        if (url.indexOf("blob:") >= 0) {
            return true;
        }

        return extensionValidation;
    };

    useEffect(() => {
        setImageUrl(props.src);
    }, [props.src]);

    useEffect(() => {
        console.log(imageUrl, isImageUrl(imageUrl));
    }, [imageUrl]);

    return (
        <div className={getClassNames()} style={props.style}>
            {!readOnly && (
                <input
                    id={props.name}
                    name={props.name}
                    accept="image/*;capture=camera"
                    type="file"
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                        const target = e.target;

                        if (!target.files) {
                            alert.showWarning("No se ha seleccionado un archivo de imagen");
                            return;
                        }

                        if (target.files && target.files.length > 0) {
                            const file = target.files[0];
                            if (!file.type.startsWith("image/")) {
                                alert.showWarning("El archivo seleccionado no es una imagen");
                                return;
                            }
                        }

                        const file = target.files[0];

                        const isUnder5MB = file.size <= mbLimit * 1024 * 1024;

                        if (!isUnder5MB) {
                            alert.showWarning(
                                `El archivo seleccionado debe ser menor de ${mbLimit} MB`
                            );
                            return;
                        }

                        setImageUrl(URL.createObjectURL(file));

                        if (props.onChange) {
                            props.onChange(e);
                        }
                    }}
                    style={{
                        width: "100%",
                        height: "100%",
                        opacity: 0,
                        position: "absolute",
                        cursor: "pointer",
                        zIndex: 10,
                    }}
                />
            )}
            {isImageUrl(imageUrl) && <img src={imageUrl} alt={props.alt} />}
            {!isImageUrl(imageUrl) && isImageUrl(imageSizeSrc) && (
                <div
                    style={{
                        position: "relative",
                        top: 0,
                        left: 0,
                        width: "100%",
                        height: "100%",
                        zIndex: 5,
                        backgroundImage: `url(${imageSizeSrc})`,
                        backgroundPosition: "center",
                        backgroundRepeat: "no-repeat",
                    }}
                >
                    &nbsp;
                </div>
            )}
        </div>
    );
}
