"use client";

import { useEffect, useState, useId } from "react";
import Link from "next/link";
import { Cookie, SlidersHorizontal, X, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  CONSENT_EVENT,
  CONSENT_KEY,
  CONSENT_PREFS_KEY,
  type CookiePreferences,
  getPreferences,
  savePreferences,
} from "@/lib/consent";
import { cn } from "@/lib/utils";

export function CookieConsent() {
  const [mounted, setMounted] = useState(false);
  const [bannerOpen, setBannerOpen] = useState(false);
  const [preferencesOpen, setPreferencesOpen] = useState(false);

  // Preference toggle states
  const [analytics, setAnalytics] = useState(false);
  const [marketing, setMarketing] = useState(false);

  const titleId = useId();
  const descId = useId();

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional: client-only check for stored consent on mount
    setMounted(true);
    let stored: string | null = null;
    try {
      stored = window.localStorage.getItem(CONSENT_KEY);
    } catch {
      stored = null;
    }

    if (!stored) {
      setBannerOpen(true);
    } else {
      const prefs = getPreferences();
      setAnalytics(prefs.analytics);
      setMarketing(prefs.marketing);
    }

    const handleOpen = () => {
      const prefs = getPreferences();
      setAnalytics(prefs.analytics);
      setMarketing(prefs.marketing);
      setPreferencesOpen(true);
    };

    window.addEventListener(CONSENT_EVENT, handleOpen);
    return () => window.removeEventListener(CONSENT_EVENT, handleOpen);
  }, []);

  // Escape key handler for preferences modal
  useEffect(() => {
    if (!preferencesOpen) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        setPreferencesOpen(false);
      }
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [preferencesOpen]);

  const acceptAll = () => {
    const prefs: CookiePreferences = {
      necessary: true,
      analytics: true,
      marketing: true,
    };
    setAnalytics(true);
    setMarketing(true);
    savePreferences(prefs);
    setBannerOpen(false);
    setPreferencesOpen(false);
  };

  const rejectAll = () => {
    const prefs: CookiePreferences = {
      necessary: true,
      analytics: false,
      marketing: false,
    };
    setAnalytics(false);
    setMarketing(false);
    savePreferences(prefs);
    setBannerOpen(false);
    setPreferencesOpen(false);
  };

  const saveCustom = () => {
    const prefs: CookiePreferences = {
      necessary: true,
      analytics,
      marketing,
    };
    savePreferences(prefs);
    setBannerOpen(false);
    setPreferencesOpen(false);
  };

  if (!mounted) return null;

  return (
    <>
      {/* ==================== STATE A: COMPACT FLOATING BANNER ==================== */}
      {bannerOpen && !preferencesOpen && (
        <aside
          role="region"
          aria-label="Cookie consent banner"
          className="fixed inset-x-0 bottom-4 sm:bottom-6 z-[70] px-4 pointer-events-none flex justify-center"
        >
          <div className="pointer-events-auto flex w-full max-w-3xl flex-col gap-3.5 rounded-2xl sm:rounded-full border border-border/80 bg-card/95 dark:bg-[#121212]/95 p-3.5 sm:p-3 sm:pl-5 sm:pr-3 shadow-float-lg backdrop-blur-md transition-all duration-300 md:flex-row md:items-center md:justify-between">
            {/* Left: Icon + Explanatory Text */}
            <div className="flex items-center gap-3">
              <div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-[var(--accent-orange-text)]/10 text-[var(--accent-orange-text)] border border-[var(--accent-orange-text)]/20">
                <Cookie className="size-4.5" />
              </div>
              <p className="text-xs sm:text-sm text-muted-foreground leading-snug">
                We use cookies to improve your experience and understand how the platform is used.
              </p>
            </div>

            {/* Right: Controls (Settings Icon, Reject All, Accept All) */}
            <div className="flex shrink-0 items-center gap-2 justify-end pt-1 sm:pt-0">
              <button
                type="button"
                onClick={() => setPreferencesOpen(true)}
                aria-label="Customize cookie settings"
                className="inline-flex size-8.5 sm:size-9 items-center justify-center rounded-full border border-border bg-secondary/60 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                title="Cookie preferences"
              >
                <SlidersHorizontal className="size-4" />
              </button>

              <button
                type="button"
                onClick={rejectAll}
                className="inline-flex h-8.5 sm:h-9 items-center justify-center rounded-full border border-border/80 bg-secondary/80 px-3.5 sm:px-4 text-xs font-semibold text-foreground transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                Reject all
              </button>

              <button
                type="button"
                onClick={acceptAll}
                className="inline-flex h-8.5 sm:h-9 items-center justify-center rounded-full bg-primary px-4 sm:px-5 text-xs font-bold text-primary-foreground shadow-xs transition-transform hover:scale-[1.02] active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                Accept all
              </button>
            </div>
          </div>
        </aside>
      )}

      {/* ==================== STATE B: DETAILED PREFERENCES MODAL ==================== */}
      {preferencesOpen && (
        <div
          role="dialog"
          aria-modal="true"
          aria-labelledby={titleId}
          aria-describedby={descId}
          className="fixed inset-0 z-[80] flex items-center justify-center bg-black/65 p-4 backdrop-blur-xs animate-in fade-in duration-200"
        >
          <div className="relative flex w-full max-w-lg flex-col rounded-3xl border border-border bg-card p-6 sm:p-7 shadow-2xl text-card-foreground max-h-[90vh] overflow-y-auto">
            {/* Header: Title & Close Button */}
            <div className="flex items-start justify-between gap-4 border-b border-border/60 pb-4">
              <div>
                <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--accent-cyan-text)]">
                  Privacy Controls
                </span>
                <h2 id={titleId} className="mt-1 font-display text-xl font-bold tracking-tight text-foreground sm:text-2xl">
                  Cookie Preferences
                </h2>
                <p id={descId} className="mt-1 text-xs sm:text-sm text-muted-foreground">
                  Adjust what you allow, then save your choice.
                </p>
              </div>

              <button
                type="button"
                onClick={() => setPreferencesOpen(false)}
                aria-label="Close cookie preferences"
                className="rounded-full p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                <X className="size-5" />
              </button>
            </div>

            {/* Categories */}
            <div className="my-5 space-y-4">
              {/* 1. Necessary */}
              <div className="rounded-2xl border border-border/60 bg-secondary/30 p-4 transition-colors">
                <div className="flex items-center justify-between gap-3">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-sm text-foreground">Necessary</span>
                  </div>
                  <span className="inline-flex items-center gap-1 rounded-full border border-emerald-500/20 bg-emerald-500/10 px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-emerald-600 dark:text-emerald-400">
                    <Check className="size-3" />
                    Always On
                  </span>
                </div>
                <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
                  Essential for basic site navigation, security features, session persistence, and network reliability. These cookies cannot be turned off.
                </p>
              </div>

              {/* 2. Analytics */}
              <div className="rounded-2xl border border-border/60 bg-secondary/30 p-4 transition-colors">
                <div className="flex items-center justify-between gap-3">
                  <span className="font-semibold text-sm text-foreground">Analytics</span>
                  <label className="relative inline-flex cursor-pointer items-center">
                    <input
                      type="checkbox"
                      checked={analytics}
                      onChange={(e) => setAnalytics(e.target.checked)}
                      className="sr-only peer"
                      aria-label="Toggle analytics cookies"
                    />
                    <div className="h-6 w-11 rounded-full bg-muted border border-border peer-checked:bg-primary peer-checked:border-primary transition-colors after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-card peer-checked:after:bg-primary-foreground after:rounded-full after:size-5 after:transition-all peer-checked:after:translate-x-full peer-focus-visible:ring-2 peer-focus-visible:ring-ring" />
                  </label>
                </div>
                <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
                  Collects anonymous usage information so we can understand popular pages, detect performance bottlenecks, and improve site experience.
                </p>
              </div>

              {/* 3. Marketing */}
              <div className="rounded-2xl border border-border/60 bg-secondary/30 p-4 transition-colors">
                <div className="flex items-center justify-between gap-3">
                  <span className="font-semibold text-sm text-foreground">Marketing</span>
                  <label className="relative inline-flex cursor-pointer items-center">
                    <input
                      type="checkbox"
                      checked={marketing}
                      onChange={(e) => setMarketing(e.target.checked)}
                      className="sr-only peer"
                      aria-label="Toggle marketing cookies"
                    />
                    <div className="h-6 w-11 rounded-full bg-muted border border-border peer-checked:bg-primary peer-checked:border-primary transition-colors after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-card peer-checked:after:bg-primary-foreground after:rounded-full after:size-5 after:transition-all peer-checked:after:translate-x-full peer-focus-visible:ring-2 peer-focus-visible:ring-ring" />
                  </label>
                </div>
                <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
                  Measures the effectiveness of campaigns and helps present relevant updates and communications across supported channels.
                </p>
              </div>
            </div>

            {/* Footer / Actions */}
            <div className="mt-2 border-t border-border/60 pt-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <Link
                href="/privacy"
                className="text-xs text-muted-foreground hover:text-foreground underline underline-offset-4"
              >
                Privacy Policy
              </Link>

              <div className="flex flex-wrap items-center gap-2 justify-end">
                <button
                  type="button"
                  onClick={rejectAll}
                  className="rounded-full border border-border px-3.5 py-1.5 text-xs font-medium text-foreground hover:bg-secondary transition-colors"
                >
                  Reject all
                </button>
                <button
                  type="button"
                  onClick={saveCustom}
                  className="rounded-full border border-border/80 bg-secondary/80 px-4 py-1.5 text-xs font-semibold text-foreground hover:bg-secondary transition-colors"
                >
                  Save choices
                </button>
                <button
                  type="button"
                  onClick={acceptAll}
                  className="rounded-full bg-primary px-4 py-1.5 text-xs font-bold text-primary-foreground hover:bg-primary/90 transition-transform active:scale-95"
                >
                  Accept all
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
