"use client";

import { useEffect, useState } from "react";
import { CookieBannerProps } from "@/types/cookie-consent";
import { saveCookieConsent } from "@/services/cookiesClientApi";

export default function CookieBanner({
  banner_message,
  accept_label,
  reject_label,
}: CookieBannerProps) {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const consent = localStorage.getItem("oculus_cookie_consent");
      if (!consent) {
        setIsVisible(true);
      }
    }
  }, []);

  const handleAccept = async () => {
    localStorage.setItem("oculus_cookie_consent", "accepted");
    document.cookie = "oculus_cookie_consent=accepted; path=/; max-age=31536000; SameSite=Lax";
    setIsVisible(false);
    try {
      await saveCookieConsent({ status: "accepted", consent: "accepted" });
    } catch (error) {
      console.error("Error saving cookie consent:", error);
    }
  };

  const handleReject = async () => {
    localStorage.setItem("oculus_cookie_consent", "rejected");
    document.cookie = "oculus_cookie_consent=rejected; path=/; max-age=31536000; SameSite=Lax";
    setIsVisible(false);
    try {
      await saveCookieConsent({ status: "rejected", consent: "rejected" });
    } catch (error) {
      console.error("Error saving cookie consent:", error);
    }
  };

  if (!isVisible || !banner_message) {
    return null;
  }

  return (
    <div
      className="fixed bottom-0 left-0 right-0 z-[999999] bg-white border-t border-[#E2E8F0] py-4 md:py-5"
      role="dialog"
      aria-label="Cookie Consent"
    >
      <div className="container mx-auto px-4">
        <div className="flex flex-col md:flex-row items-center justify-between gap-4">
          {/* Banner Message */}
          <div className="text-[14px] md:text-[15px] text-[#334D72] font-medium leading-relaxed text-center md:text-left flex-1">
            <p>{banner_message}</p>
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-3 shrink-0 w-full md:w-auto justify-center md:justify-end">
            {reject_label && (
              <button
                type="button"
                onClick={handleReject}
                className="px-4 py-2 rounded-[8px] bg-[#e5e5e5] text-[#000] text-[14px] font-bold transition-all cursor-pointer whitespace-nowrap outline-none"
              >
                {reject_label}
              </button>
            )}
            {accept_label && (
              <button
                type="button"
                onClick={handleAccept}
                className="px-4 py-2 rounded-[8px] bg-[#1718FF] text-white text-[14px] font-bold transition-all cursor-pointer whitespace-nowrap outline-none shadow-sm"
              >
                {accept_label}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
