import { animated, useTransition } from "@react-spring/web";
import {
  leadershipUtils,
  leadershipStatus,
} from "../../features/context/TOD.FormulaireData.js";
import "./LeaderOverlay.css";

const useState = wp.element.useState;
const useEffect = wp.element.useEffect;

const LeaderOverlay = () => {
  const [isVisible, setIsVisible] = useState(false);
  const [isClaimingLeadership, setIsClaimingLeadership] = useState(false);

  // Surveiller le statut de leadership
  useEffect(() => {
    setIsVisible(!leadershipStatus.value.isLeader);
  }, [leadershipStatus.value.isLeader]);

  const transitions = useTransition(isVisible, {
    from: { opacity: 0, transform: "scale(0.95)" },
    enter: { opacity: 1, transform: "scale(1)" },
    leave: { opacity: 0, transform: "scale(0.95)" },
    config: { tension: 300, friction: 30 },
  });

  const handleClaimLeadership = async () => {
    setIsClaimingLeadership(true);

    try {
      const response = await leadershipUtils.claimLeadership(true); // force = true

      if (response.success) {
        console.log("Leadership pris avec succès !");
        // Le signal sera automatiquement mis à jour
      } else {
        console.error(
          "Erreur lors de la prise de leadership:",
          response.message
        );
      }
    } catch (error) {
      console.error("Erreur lors de la prise de leadership:", error);
    } finally {
      setIsClaimingLeadership(false);
    }
  };

  const currentLeader = leadershipStatus.value.currentLeader;
  const pageIdShort = leadershipStatus.value.pageId?.slice(-8) || "N/A";

  return (
    <>
      {transitions(
        (style, item) =>
          item && (
            <animated.div style={style} className="wb-leader-overlay">
              <div className="wb-leader-overlay-backdrop"></div>
              <div className="wb-leader-overlay-content">
                <div className="wb-leader-overlay-card">
                  <h3 className="wb-leader-overlay-title">
                    The website builder is active in another window
                  </h3>

                  <p className="wb-leader-overlay-description">
                    To avoid conflicts, only one user can use the website
                    builder at once.
                  </p>

                  <div className="wb-leader-overlay-actions">
                    <button
                      className="wb-leader-overlay-btn wb-leader-overlay-btn-primary"
                      onClick={handleClaimLeadership}
                      disabled={isClaimingLeadership}
                    >
                      {isClaimingLeadership ? (
                        <>
                          <span className="wb-leader-overlay-spinner"></span>
                          Taking over...
                        </>
                      ) : (
                        "Take over in this window"
                      )}
                    </button>
                  </div>
                </div>
              </div>
            </animated.div>
          )
      )}
    </>
  );
};

export default LeaderOverlay;
