/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState, useEffect, ComponentType, useRef, Ref } from "react";
import "react-quill-new/dist/quill.snow.css";
import "./quill.i18n.css";
import { uploadPostFile } from "./QuillEditor.Service";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { useOrgDataStore } from "@core/Store/OrganizationData.Store";

interface QuillEditorProps {
    value: string;
    onChange: (value: string) => void;
}

const translations = {
    bold: "Negrita",
    italic: "Cursiva",
    underline: "Subrayado",
    strike: "Tachado",
    blockquote: "Cita",
    list: "Lista",
    indent: "Sangría",
    link: "Enlace",
    image: "Imagen",
    video: "Video",
    clean: "Limpiar formato",
    color: "Color de fuente",
    background: "Color de fondo",
    header: "Encabezado",
    size: "Tamaño de fuente",
} as const;

interface QuillComponentProps {
    theme: string;
    value: string;
    onChange: (value: string) => void;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    modules: any;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    ref?: Ref<any>;
}

const QuillEditor: React.FC<QuillEditorProps> = ({ value, onChange }) => {
    const [Quill, setQuill] = useState<ComponentType<QuillComponentProps> | null>(null);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const quillRef = useRef<any>(null); // Ref to Quill instance
    const SessionInfo = useSessionStore();
    const OrganizationData = useOrgDataStore();

    useEffect(() => {
        import("react-quill-new").then((mod) => {
            setQuill(() => mod.default as unknown as ComponentType<QuillComponentProps>);
        });
    }, []);

    useEffect(() => {
        if (Quill) {
            const timer = setTimeout(() => {
                const toolbar = document.querySelector(".ql-toolbar");
                if (toolbar) {
                    Object.keys(translations).forEach((format) => {
                        const elements = toolbar.querySelectorAll(`.ql-${format}`);
                        elements.forEach((el) => {
                            if (el instanceof HTMLElement) {
                                el.title = translations[format as keyof typeof translations];
                            }
                        });
                    });
                }
            }, 100);
            return () => clearTimeout(timer);
        }
    }, [Quill]);

    const imageHandler = () => {
        const input = document.createElement("input");
        input.setAttribute("type", "file");
        input.setAttribute("accept", "image/*");
        input.click();

        input.onchange = async () => {
            const file = input.files ? input.files[0] : null;
            if (file) {
                // Simulate upload to backend
                const imageUrl = await new Promise<string>((resolve) => {
                    uploadPostFile({
                        sessionUser: SessionInfo.userId,
                        token: SessionInfo.userToken,
                        companyId: `${OrganizationData.orgData?.id}`,
                        file: file,
                    })
                        .then((response) => {
                            const host = process.env.NEXT_PUBLIC_API_URL || "";
                            resolve(host + "files/download/" + response.files[0].objectName);
                        })
                        .catch((error) => {
                            console.log("Error uploading image:", error);
                            resolve("");
                        });
                });

                const editor = quillRef.current.getEditor();
                const range = editor.getSelection();
                if (range) {
                    editor.insertEmbed(range.index, "image", imageUrl);
                }
            }
        };
    };

    const videoHandler = () => {
        const url = window.prompt("Introduce la URL del video (YouTube, Vimeo, etc.):");

        if (url && quillRef.current) {
            const editor = quillRef.current.getEditor();
            const range = editor.getSelection();

            if (range) {
                // Verificar si es una URL de YouTube
                let embedUrl = url;

                // Convertir URLs de YouTube a formato embed si es necesario
                if (url.includes('youtube.com/watch')) {
                    const videoId = url.split('v=')[1];
                    const ampersandPosition = videoId.indexOf('&');
                    if (ampersandPosition !== -1) {
                        embedUrl = `https://www.youtube.com/embed/${videoId.substring(0, ampersandPosition)}`;
                    } else {
                        embedUrl = `https://www.youtube.com/embed/${videoId}`;
                    }
                } else if (url.includes('youtu.be/')) {
                    const videoId = url.split('youtu.be/')[1];
                    embedUrl = `https://www.youtube.com/embed/${videoId}`;
                } else if (url.includes('vimeo.com/')) {
                    const videoId = url.split('vimeo.com/')[1];
                    // Si es una URL de Vimeo con subdirectorios
                    if (videoId.includes('/')) {
                        const parts = videoId.split('/');
                        embedUrl = `https://player.vimeo.com/video/${parts[parts.length - 1]}`;
                    } else {
                        embedUrl = `https://player.vimeo.com/video/${videoId}`;
                    }
                }

                // Insertar el video como iframe
                editor.insertEmbed(range.index, "video", embedUrl);
                // Mover el cursor después del video
                editor.setSelection(range.index + 1);
            }
        }
    };

    const modules = {
        toolbar: {
            container: [
                [{ header: "1" }, { header: "2" }],
                [{ size: [] }],
                ["bold", "italic", "underline", "strike", "blockquote"],
                [{ list: "ordered" }, { list: "bullet" }, { indent: "-1" }, { indent: "+1" }],
                ["link", "image", "video"],
                ["clean"],
                [{ color: [] }, { background: [] }],
            ],
            handlers: {
                image: imageHandler,
                video: videoHandler,
            },
        },
    };

    if (!Quill) {
        return null;
    }

    return (
        <div className="quill-wrapper" style={{ height: "100%", width: "100%" }}>
            <style jsx global>{`
                .quill-wrapper {
                    display: flex;
                    flex-direction: column;
                    height: 100%;
                    width: 100%;
                }
                .quill-wrapper .ql-tooltip {
                    z-index: 2; /* Higher than toolbar's z-index */
                    top: 42px !important; /* Push it down below the toolbar */
                }
                .quill-wrapper .ql-toolbar {
                    flex-shrink: 0;
                    border-bottom: 1px solid #ccc; /* Add a border for separation */
                    position: sticky; /* Make toolbar sticky */
                    top: 0; /* Stick to the top */
                    z-index: 1; /* Ensure it's above content */
                    background-color: white; /* Ensure background is solid */
                }
                .quill-wrapper .ql-container {
                    flex-grow: 1;
                    overflow-y: auto; /* Make the container scrollable */
                    display: flex;
                    flex-direction: column;
                }
                .quill-wrapper .ql-editor {
                    flex-grow: 1;
                    /* overflow-y: auto; This is now handled by ql-container */
                }

                /* Estilos para videos dentro del editor */
        .quill-wrapper .ql-editor .ql-video {
            display: block;
            max-width: 100%;
            margin: 16px 0;
        }
        
        .quill-wrapper .ql-editor .ql-video iframe {
            width: 100%;
            min-height: 300px;
            border: 0;
            border-radius: 8px;
        }
        
        /* Estilos para imágenes dentro del editor */
        .quill-wrapper .ql-editor img {
            max-width: 100%;
            height: auto;
            display: block;
            margin: 16px 0;
            border-radius: 8px;
        }
        
        /* Para mejor experiencia de edición, agregar un borde alrededor de elementos embebidos */
        .quill-wrapper .ql-editor .ql-video,
        .quill-wrapper .ql-editor img {
            outline: 2px dashed transparent;
            transition: outline-color 0.2s;
        }
        
        .quill-wrapper .ql-editor .ql-video:hover,
        .quill-wrapper .ql-editor img:hover {
            outline-color: #4d90fe;
        }
        
        /* Mostrar cursor de texto sobre elementos para indicar que se pueden editar/eliminar */
        .quill-wrapper .ql-editor .ql-video::after,
        .quill-wrapper .ql-editor img::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            cursor: text;
        }
            `}</style>
            <Quill
                ref={quillRef}
                theme="snow"
                value={value}
                onChange={onChange}
                modules={modules}
            />
        </div>
    );
};

export default QuillEditor;
