import { useState, useEffect, useCallback } from "react";
import { X, Cookie, ChevronDown, ChevronUp, Shield, BarChart3, Megaphone } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
import {
  type CookiePreferences,
  getStoredConsent,
  getDefaultPreferences,
  saveConsent,
  acceptAll,
  rejectAll,
  hasConsent,
} from "@/lib/cookieConsent";

interface CookieCategoryProps {
  icon: React.ReactNode;
  title: string;
  description: string;
  enabled: boolean;
  locked?: boolean;
  onToggle: () => void;
}

function CookieCategory({ icon, title, description, enabled, locked, onToggle }: CookieCategoryProps) {
  return (
    <div className="flex items-start gap-3 py-3">
      <div className="mt-0.5 text-teal shrink-0">{icon}</div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between gap-2">
          <span className="font-medium text-sm text-navy">{title}</span>
          <button
            type="button"
            onClick={onToggle}
            disabled={locked}
            className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-teal focus-visible:ring-offset-2 ${
              locked ? "cursor-not-allowed opacity-60" : ""
            } ${enabled ? "bg-teal" : "bg-gray-300"}`}
            role="switch"
            aria-checked={enabled}
            aria-label={`Toggle ${title}`}
          >
            <span
              className={`pointer-events-none block h-4 w-4 rounded-full bg-white shadow-sm ring-0 transition-transform ${
                enabled ? "ltr:translate-x-[18px] rtl:-translate-x-[18px]" : "ltr:translate-x-[2px] rtl:-translate-x-[2px]"
              }`}
            />
          </button>
        </div>
        <p className="text-xs text-gray-500 mt-0.5 leading-relaxed">{description}</p>
      </div>
    </div>
  );
}

export default function CookieConsent() {
  const { t, lang } = useLanguage();
  const [visible, setVisible] = useState(false);
  const [showDetails, setShowDetails] = useState(false);
  const [preferences, setPreferences] = useState<CookiePreferences>(getDefaultPreferences());

  useEffect(() => {
    // Show banner if no consent record exists
    if (!hasConsent()) {
      // Small delay for better UX — don't flash immediately on load
      const timer = setTimeout(() => setVisible(true), 1200);
      return () => clearTimeout(timer);
    } else {
      const stored = getStoredConsent();
      if (stored) setPreferences(stored.preferences);
    }
  }, []);

  const handleAcceptAll = useCallback(() => {
    const record = acceptAll();
    setPreferences(record.preferences);
    setVisible(false);
    // Dispatch custom event so analytics can react
    window.dispatchEvent(new CustomEvent("cookie-consent-updated", { detail: record.preferences }));
  }, []);

  const handleRejectAll = useCallback(() => {
    const record = rejectAll();
    setPreferences(record.preferences);
    setVisible(false);
    window.dispatchEvent(new CustomEvent("cookie-consent-updated", { detail: record.preferences }));
  }, []);

  const handleSavePreferences = useCallback(() => {
    const record = saveConsent(preferences);
    setVisible(false);
    window.dispatchEvent(new CustomEvent("cookie-consent-updated", { detail: record.preferences }));
  }, [preferences]);

  const toggleCategory = useCallback((category: keyof CookiePreferences) => {
    if (category === "essential") return; // Cannot toggle essential
    setPreferences((prev) => ({ ...prev, [category]: !prev[category] }));
  }, []);

  // Allow external trigger to re-open the banner (from footer link)
  useEffect(() => {
    const handler = () => {
      const stored = getStoredConsent();
      if (stored) setPreferences(stored.preferences);
      else setPreferences(getDefaultPreferences());
      setShowDetails(true);
      setVisible(true);
    };
    window.addEventListener("open-cookie-settings", handler);
    return () => window.removeEventListener("open-cookie-settings", handler);
  }, []);

  if (!visible) return null;

  const isAr = lang === "ar";

  return (
    <div className="fixed inset-0 z-[9999] pointer-events-none">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/30 backdrop-blur-[2px] pointer-events-auto"
        onClick={handleRejectAll}
      />

      {/* Banner */}
      <div
        className="absolute bottom-0 left-0 right-0 pointer-events-auto animate-in slide-in-from-bottom duration-500"
        dir={isAr ? "rtl" : "ltr"}
      >
        <div className="bg-white border-t border-gray-200 shadow-2xl">
          <div className="container max-w-5xl py-5 px-4 sm:px-6">
            {/* Header row */}
            <div className="flex items-start gap-3 mb-3">
              <Cookie className="w-6 h-6 text-teal shrink-0 mt-0.5" />
              <div className="flex-1">
                <h3 className="font-heading font-semibold text-navy text-base">
                  {isAr ? "نحن نقدر خصوصيتك" : "We Value Your Privacy"}
                </h3>
                <p className="text-sm text-gray-600 mt-1 leading-relaxed">
                  {isAr
                    ? "نستخدم ملفات تعريف الارتباط لتحسين تجربة التصفح وتحليل حركة المرور على الموقع. يمكنك اختيار ملفات تعريف الارتباط التي تسمح بها."
                    : "We use cookies to enhance your browsing experience and analyze site traffic. You can choose which cookies you allow."}
                </p>
              </div>
              <button
                onClick={handleRejectAll}
                className="text-gray-400 hover:text-gray-600 transition-colors shrink-0"
                aria-label="Close"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Expandable details */}
            <button
              type="button"
              onClick={() => setShowDetails(!showDetails)}
              className="flex items-center gap-1.5 text-sm text-teal hover:text-teal-dark transition-colors mb-3 font-medium"
            >
              {isAr ? "تخصيص الإعدادات" : "Customize Settings"}
              {showDetails ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
            </button>

            {showDetails && (
              <div className="border border-gray-100 rounded-lg bg-gray-50/50 px-4 py-1 mb-4 divide-y divide-gray-100">
                <CookieCategory
                  icon={<Shield className="w-4 h-4" />}
                  title={isAr ? "ملفات تعريف الارتباط الأساسية" : "Essential Cookies"}
                  description={
                    isAr
                      ? "ضرورية لعمل الموقع. تتضمن تفضيلات اللغة وحماية النماذج. لا يمكن تعطيلها."
                      : "Required for the website to function. Includes language preferences and form protection. Cannot be disabled."
                  }
                  enabled={true}
                  locked={true}
                  onToggle={() => {}}
                />
                <CookieCategory
                  icon={<BarChart3 className="w-4 h-4" />}
                  title={isAr ? "ملفات تعريف الارتباط التحليلية" : "Analytics Cookies"}
                  description={
                    isAr
                      ? "تساعدنا على فهم كيفية استخدام الزوار للموقع من خلال جمع معلومات مجهولة الهوية (Google Analytics)."
                      : "Help us understand how visitors use the site by collecting anonymous information (Google Analytics)."
                  }
                  enabled={preferences.analytics}
                  onToggle={() => toggleCategory("analytics")}
                />
                <CookieCategory
                  icon={<Megaphone className="w-4 h-4" />}
                  title={isAr ? "ملفات تعريف الارتباط التسويقية" : "Marketing Cookies"}
                  description={
                    isAr
                      ? "تُستخدم لتقديم إعلانات ذات صلة وقياس فعالية الحملات التسويقية."
                      : "Used to deliver relevant advertisements and measure the effectiveness of marketing campaigns."
                  }
                  enabled={preferences.marketing}
                  onToggle={() => toggleCategory("marketing")}
                />
              </div>
            )}

            {/* Action buttons */}
            <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3">
              <button
                onClick={handleAcceptAll}
                className="px-5 py-2.5 bg-teal hover:bg-teal-dark text-white text-sm font-semibold rounded-lg transition-colors shadow-sm"
              >
                {isAr ? "قبول الكل" : "Accept All"}
              </button>
              {showDetails ? (
                <button
                  onClick={handleSavePreferences}
                  className="px-5 py-2.5 bg-navy hover:bg-navy-light text-white text-sm font-semibold rounded-lg transition-colors shadow-sm"
                >
                  {isAr ? "حفظ التفضيلات" : "Save Preferences"}
                </button>
              ) : null}
              <button
                onClick={handleRejectAll}
                className="px-5 py-2.5 border border-gray-300 hover:border-gray-400 text-gray-700 text-sm font-medium rounded-lg transition-colors bg-white"
              >
                {isAr ? "رفض الاختيارية" : "Reject Optional"}
              </button>
              <a
                href="/cookie-policy"
                className="text-sm text-teal hover:text-teal-dark underline underline-offset-2 sm:ms-auto transition-colors"
              >
                {isAr ? "سياسة ملفات تعريف الارتباط" : "Cookie Policy"}
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
