"use client";

import React, { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import styles from "./CookieConsent.module.css";

export default function CookieConsent({ data }: { data?: any }) {
  const [isVisible, setIsVisible] = useState(false);

  const globals = data?.included?.globals;
  const cookieData = globals?.cookieConsent;

  const consentText = cookieData?.text || "We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. Learn more in our";
  const privacyLabel = cookieData?.privacyLabel || "Privacy Policy";
  const privacyHref = cookieData?.privacyHref || "#";
  const declineLabel = cookieData?.declineLabel || "Decline";
  const acceptLabel = cookieData?.acceptLabel || "Accept All";

  useEffect(() => {
    // Check if user has already made a choice using browser cookies
    const getCookie = (name: string) => {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      if (parts.length === 2) return parts.pop()?.split(";").shift();
      return null;
    };

    const consent = getCookie("scilly_cookie_consent");
    if (!consent) {
      // Small delay before showing the banner
      const timer = setTimeout(() => {
        setIsVisible(true);
      }, 1500);
      return () => clearTimeout(timer);
    }
  }, []);

  const setConsentCookie = (value: string) => {
    const date = new Date();
    date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)); // 1 year expiry
    const expires = "expires=" + date.toUTCString();
    document.cookie = `scilly_cookie_consent=${value}; ${expires}; path=/; SameSite=Lax`;
  };

  const handleAccept = () => {
    setConsentCookie("accepted");
    setIsVisible(false);
  };

  const handleDecline = () => {
    setConsentCookie("declined");
    setIsVisible(false);
  };

  return (
    <AnimatePresence>
      {isVisible && (
        <motion.div
          initial={{ y: 100, x: "-50%", opacity: 0 }}
          animate={{ y: 0, x: "-50%", opacity: 1 }}
          exit={{ y: 100, x: "-50%", opacity: 0 }}
          transition={{ duration: 0.6, ease: [0.22, 1, 0.36, 1] }}
          className={styles.container}
        >
          <p className={styles.text}>
            {consentText} <a href={privacyHref}>{privacyLabel}</a>.
          </p>
          <div className={styles.buttonGroup}>
            <button
              onClick={handleDecline}
              className={styles.declineButton}
              type="button"
            >
              {declineLabel}
            </button>
            <button
              onClick={handleAccept}
              className={styles.acceptButton}
              type="button"
            >
              {acceptLabel}
            </button>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
