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

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

export const Anchoring = (props: AnchoringProps) => {
  const [opacity, setOpacity] = useState(1);
  const anchoringRef = useRef(null);

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

  const handleScrollClick = () => {
    anchoringRef.current.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 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"
    }
  ]
};