import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Link } from "react-router-dom";

const CONSENT_KEY = "chatsku_cookie_consent";

type ConsentStatus = "accepted" | "declined" | null;

const getConsent = (): ConsentStatus => {
  return localStorage.getItem(CONSENT_KEY) as ConsentStatus;
};

const enableAnalytics = () => {
  window.gtag?.("consent", "update", {
    analytics_storage: "granted",
  });
};

const disableAnalytics = () => {
  window.gtag?.("consent", "update", {
    analytics_storage: "denied",
  });
};

declare global {
  interface Window {
    gtag?: (...args: unknown[]) => void;
  }
}

const CookieConsent = () => {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const consent = getConsent();
    if (consent === null) {
      setVisible(true);
      disableAnalytics();
    } else if (consent === "accepted") {
      enableAnalytics();
    } else {
      disableAnalytics();
    }
  }, []);

  const handleAccept = () => {
    localStorage.setItem(CONSENT_KEY, "accepted");
    enableAnalytics();
    setVisible(false);
  };

  const handleDecline = () => {
    localStorage.setItem(CONSENT_KEY, "declined");
    disableAnalytics();
    setVisible(false);
  };

  if (!visible) return null;

  return (
    <div className="fixed bottom-0 left-0 right-0 z-[100] p-4 animate-in slide-in-from-bottom-4 duration-500">
      <div className="mx-auto max-w-4xl rounded-xl border border-border bg-background/95 backdrop-blur-md p-4 sm:p-6 shadow-2xl flex flex-col sm:flex-row items-start sm:items-center gap-4">
        <div className="flex-1 text-sm text-muted-foreground">
          <p>
            We use cookies and Google Analytics to understand how you use our site and improve your experience.
            By accepting, you consent to analytics tracking. See our{" "}
            <Link to="/privacy" className="text-primary underline underline-offset-2 hover:text-primary/80">
              Privacy Policy
            </Link>{" "}
            for details.
          </p>
        </div>
        <div className="flex gap-2 shrink-0">
          <Button variant="outline" size="sm" onClick={handleDecline}>
            Decline
          </Button>
          <Button size="sm" onClick={handleAccept}>
            Accept
          </Button>
        </div>
      </div>
    </div>
  );
};

export default CookieConsent;
