import * as React from "react";
import { useEffect, useRef, useState } from "react";
import { tinaField } from "tinacms/dist/react";
import { ObjectField } from "@tinacms/schema-tools/dist/types";

interface AnchoringProps {
  text?: string, // Default: Découvrez-en plus !
  linkTo?: string // Default: #main-page
}

/**
 * Made to be used with the carousel
 * @param {AnchoringProps} props Props for the anchoring.
 * @return {ReactElement} The function component
 */
export const Anchoring: React.FC<AnchoringProps> = (props) => {
    const [opacity, setOpacity] = useState(1);
    const anchoringRef = useRef<HTMLDivElement>(null);

    const handleScrollOpacity = () => {
        const scrollTop = window.scrollY || window.pageYOffset;
        const elementHeight = anchoringRef.current?.clientHeight ? anchoringRef.current.clientHeight : 1;
        const newOpacity = (elementHeight - scrollTop) / elementHeight;
        setOpacity(newOpacity);
    };

    const handleScrollClick = () => {
        const nextSection = anchoringRef?.current?.closest("section")?.parentElement?.nextElementSibling;
        nextSection?.scrollIntoView({
            behavior: "smooth",
            block: "start"
        });
    };

    useEffect(() => {
        handleScrollOpacity(); // Initialize opacity on mount

        window.addEventListener("scroll", handleScrollOpacity);

        return () => {
            window.removeEventListener("scroll", handleScrollOpacity);
        };
    }, []);

    return (
        <div
            className="anchoring"
            ref={ anchoringRef }
            style={ { opacity: opacity } }
        >
            <a role="button" onClick={ handleScrollClick }>
                <h1 data-tina-field={ tinaField(props, "text") }>{ props.text }</h1>
                <img
                    src="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMjQgMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTExLjI1OCAxNi4yNDItNi02YTEuMDUgMS4wNSAwIDEgMSAxLjQ4NC0xLjQ4NEwxMiAxNC4wMTVsNS4yNTgtNS4yNTdhMS4wNSAxLjA1IDAgMSAxIDEuNDg0IDEuNDg0bC02IDZhMS4wNSAxLjA1IDAgMCAxLTEuNDg0IDBaIiBmaWxsPSIjZmZmZmZmIiBmaWxsLXJ1bGU9Im5vbnplcm8iIGNsYXNzPSJmaWxsLTAwMDAwMCI+PC9wYXRoPjwvc3ZnPg=="/>
            </a>
        </div>
    );
};

export const anchoringSchema: ObjectField = {
    type: "object",
    label: "Lien",
    name: "link",
    ui: {
        defaultItem: {
            text: "Découvrez-en plus !",
            linkTo: "#main-page",
            enabled: true
        }
    },
    fields: [
        {
            type: "boolean",
            label: "Active",
            name: "enabled"
        },
        {
            type: "string",
            label: "Texte",
            name: "text"
        },
        {
            type: "string",
            label: "Lien",
            name: "linkTo"
        }
    ]
};