"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { type Lang } from "@/lib/config";
import { XMarkIcon, Cog6ToothIcon } from "@heroicons/react/24/outline";

interface CookiePreferences {
  essential: boolean;
  analytics: boolean;
  functional: boolean;
}

interface CookieConsentProps {
  lang: Lang;
}

export default function CookieConsent({ lang }: CookieConsentProps) {
  const [isVisible, setIsVisible] = useState(false);
  const [showCustomize, setShowCustomize] = useState(false);
  const [preferences, setPreferences] = useState<CookiePreferences>({
    essential: true, // Always true, cannot be disabled
    analytics: true,
    functional: true,
  });

  const isAr = lang === "ar";

  useEffect(() => {
    // Check if user has already made a choice
    const consent = localStorage.getItem("cookie_consent");
    if (!consent) {
      // Show banner after a short delay for better UX
      const timer = setTimeout(() => setIsVisible(true), 1000);
      return () => clearTimeout(timer);
    }
  }, []);

  // Auto-dismiss cookie banner after 8 seconds to prevent blocking UI
  useEffect(() => {
    if (isVisible) {
      const autoDismissTimer = setTimeout(() => {
        console.log("Auto-dismissing cookie banner to prevent UI blocking");
        handleAcceptAll();
      }, 8000); // 8 seconds

      return () => clearTimeout(autoDismissTimer);
    }
  }, [isVisible]);

  const savePreferences = (prefs: CookiePreferences) => {
    const consentData = {
      timestamp: new Date().toISOString(),
      preferences: prefs,
    };
    localStorage.setItem("cookie_consent", JSON.stringify(consentData));

    // Set cookie to remember consent (1 year expiry)
    const expiryDate = new Date();
    expiryDate.setFullYear(expiryDate.getFullYear() + 1);
    document.cookie = `cookie_consent=${JSON.stringify(prefs)}; expires=${expiryDate.toUTCString()}; path=/; SameSite=Lax`;

    // Load or unload analytics based on preference
    if (prefs.analytics) {
      loadGoogleAnalytics();
    }

    setIsVisible(false);
  };

  const handleAcceptAll = () => {
    savePreferences({
      essential: true,
      analytics: true,
      functional: true,
    });
  };

  const handleRejectAll = () => {
    savePreferences({
      essential: true,
      analytics: false,
      functional: false,
    });
  };

  const handleSaveCustom = () => {
    savePreferences(preferences);
  };

  const loadGoogleAnalytics = () => {
    // Only load if GA ID is configured
    const gaId = process.env.NEXT_PUBLIC_GA_ID;
    if (!gaId) return;

    // Check if already loaded
    if (
      document.querySelector(
        `script[src*="googletagmanager.com/gtag/js?id=${gaId}"]`,
      )
    ) {
      return;
    }

    // Load Google Analytics
    const script1 = document.createElement("script");
    script1.async = true;
    script1.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}`;
    document.head.appendChild(script1);

    const script2 = document.createElement("script");
    script2.innerHTML = `
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', '${gaId}', {
        anonymize_ip: true,
        cookie_flags: 'SameSite=Lax;Secure'
      });
    `;
    document.head.appendChild(script2);
  };

  if (!isVisible) return null;

  return (
    <>
      {/* Cookie Consent Dialog - No backdrop to avoid blocking page */}
      <div className="fixed inset-x-0 bottom-0 z-50 animate-slideUp">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 pb-6">
          <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl border-2 border-brand-green/20 overflow-hidden">
            {!showCustomize ? (
              // Simple Accept/Reject View
              <div className="p-6 sm:p-8">
                <div className="flex items-start justify-between gap-4 mb-4">
                  <div className="flex items-center gap-3">
                    <span className="text-4xl">🍪</span>
                    <h3 className="text-2xl font-bold text-brand-ink dark:text-white">
                      {isAr
                        ? "نحن نستخدم ملفات تعريف الارتباط"
                        : "We Use Cookies"}
                    </h3>
                  </div>
                  <button
                    onClick={handleRejectAll}
                    className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 transition-colors"
                    aria-label={isAr ? "إغلاق" : "Close"}
                  >
                    <XMarkIcon className="h-6 w-6" />
                  </button>
                </div>

                <p className="text-slate-600 dark:text-slate-300 mb-6 text-base leading-relaxed">
                  {isAr
                    ? "نستخدم ملفات تعريف الارتباط الأساسية للوظائف الأساسية وملفات تعريف الارتباط الاختيارية لتحسين تجربتك. يمكنك قبول جميع ملفات تعريف الارتباط أو رفضها أو تخصيص تفضيلاتك."
                    : "We use essential cookies for core functionality and optional cookies to improve your experience. You can accept all, reject all, or customize your preferences."}
                </p>

                <div className="flex flex-col sm:flex-row gap-3">
                  <button
                    onClick={handleAcceptAll}
                    className="flex-1 px-6 py-3 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-600 transition-all duration-200 transform hover:scale-105 shadow-lg"
                  >
                    {isAr ? "قبول الكل" : "Accept All"}
                  </button>

                  <button
                    onClick={handleRejectAll}
                    className="flex-1 px-6 py-3 bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-200 font-semibold rounded-lg hover:bg-slate-300 dark:hover:bg-slate-600 transition-colors"
                  >
                    {isAr ? "رفض الكل" : "Reject All"}
                  </button>

                  <button
                    onClick={() => setShowCustomize(true)}
                    className="flex-1 px-6 py-3 border-2 border-brand-green text-brand-green font-semibold rounded-lg hover:bg-brand-green hover:text-white transition-all duration-200 flex items-center justify-center gap-2"
                  >
                    <Cog6ToothIcon className="h-5 w-5" />
                    {isAr ? "تخصيص" : "Customize"}
                  </button>
                </div>

                <p className="text-xs text-slate-500 dark:text-slate-400 mt-4 text-center">
                  {isAr ? "لمعرفة المزيد، اقرأ" : "Learn more in our"}{" "}
                  <Link
                    href={`/${lang}/cookies`}
                    className="text-brand-green hover:underline font-medium"
                  >
                    {isAr ? "سياسة ملفات تعريف الارتباط" : "Cookie Policy"}
                  </Link>
                </p>
              </div>
            ) : (
              // Customize View
              <div className="p-6 sm:p-8">
                <div className="flex items-start justify-between gap-4 mb-6">
                  <div>
                    <h3 className="text-2xl font-bold text-brand-ink dark:text-white mb-2">
                      {isAr
                        ? "تخصيص تفضيلات ملفات تعريف الارتباط"
                        : "Customize Cookie Preferences"}
                    </h3>
                    <p className="text-sm text-slate-600 dark:text-slate-300">
                      {isAr
                        ? "اختر فئات ملفات تعريف الارتباط التي تريد السماح بها"
                        : "Choose which cookie categories you want to allow"}
                    </p>
                  </div>
                  <button
                    onClick={() => setShowCustomize(false)}
                    className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 transition-colors"
                    aria-label={isAr ? "رجوع" : "Back"}
                  >
                    <XMarkIcon className="h-6 w-6" />
                  </button>
                </div>

                <div className="space-y-4 mb-6">
                  {/* Essential Cookies */}
                  <div className="bg-slate-50 dark:bg-slate-900 rounded-lg p-4 border border-slate-200 dark:border-slate-700">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <span className="text-2xl">🔐</span>
                          <h4 className="font-semibold text-brand-ink dark:text-white">
                            {isAr
                              ? "ملفات تعريف الارتباط الأساسية"
                              : "Essential Cookies"}
                          </h4>
                          <span className="px-2 py-0.5 bg-brand-green text-white text-xs font-semibold rounded">
                            {isAr ? "مطلوب" : "Required"}
                          </span>
                        </div>
                        <p className="text-sm text-slate-600 dark:text-slate-300">
                          {isAr
                            ? "ضرورية لعمل الموقع بشكل صحيح. لا يمكن تعطيلها."
                            : "Necessary for the website to function properly. Cannot be disabled."}
                        </p>
                      </div>
                      <div className="relative inline-block w-12 h-6 flex-shrink-0">
                        <input
                          type="checkbox"
                          aria-label={isAr ? "ملفات تعريف الارتباط الضرورية (مطلوبة)" : "Necessary cookies (required)"}
                          checked={true}
                          disabled
                          className="sr-only"
                        />
                        <div className="w-12 h-6 bg-brand-green rounded-full shadow-inner opacity-50 cursor-not-allowed"></div>
                        <div className="absolute left-6 top-0.5 bg-white w-5 h-5 rounded-full shadow"></div>
                      </div>
                    </div>
                  </div>

                  {/* Analytics Cookies */}
                  <div className="bg-slate-50 dark:bg-slate-900 rounded-lg p-4 border border-slate-200 dark:border-slate-700">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <span className="text-2xl">📊</span>
                          <h4 className="font-semibold text-brand-ink dark:text-white">
                            {isAr
                              ? "ملفات تعريف ارتباط التحليلات"
                              : "Analytics Cookies"}
                          </h4>
                        </div>
                        <p className="text-sm text-slate-600 dark:text-slate-300">
                          {isAr
                            ? "تساعدنا على فهم كيفية استخدام الزوار لموقعنا (Google Analytics)."
                            : "Help us understand how visitors use our website (Google Analytics)."}
                        </p>
                      </div>
                      <button
                        onClick={() =>
                          setPreferences((prev) => ({
                            ...prev,
                            analytics: !prev.analytics,
                          }))
                        }
                        className="relative inline-block w-12 h-6 flex-shrink-0"
                        role="switch"
                        aria-checked={preferences.analytics}
                      >
                        <div
                          className={`w-12 h-6 rounded-full shadow-inner transition-colors ${
                            preferences.analytics
                              ? "bg-brand-green"
                              : "bg-slate-300 dark:bg-slate-600"
                          }`}
                        ></div>
                        <div
                          className={`absolute top-0.5 bg-white w-5 h-5 rounded-full shadow transition-transform ${
                            preferences.analytics ? "left-6" : "left-0.5"
                          }`}
                        ></div>
                      </button>
                    </div>
                  </div>

                  {/* Functional Cookies */}
                  <div className="bg-slate-50 dark:bg-slate-900 rounded-lg p-4 border border-slate-200 dark:border-slate-700">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <span className="text-2xl">⚙️</span>
                          <h4 className="font-semibold text-brand-ink dark:text-white">
                            {isAr
                              ? "ملفات تعريف الارتباط الوظيفية"
                              : "Functional Cookies"}
                          </h4>
                        </div>
                        <p className="text-sm text-slate-600 dark:text-slate-300">
                          {isAr
                            ? "تتذكر تفضيلاتك مثل السمة واللغة."
                            : "Remember your preferences like theme and language."}
                        </p>
                      </div>
                      <button
                        onClick={() =>
                          setPreferences((prev) => ({
                            ...prev,
                            functional: !prev.functional,
                          }))
                        }
                        className="relative inline-block w-12 h-6 flex-shrink-0"
                        role="switch"
                        aria-checked={preferences.functional}
                      >
                        <div
                          className={`w-12 h-6 rounded-full shadow-inner transition-colors ${
                            preferences.functional
                              ? "bg-brand-green"
                              : "bg-slate-300 dark:bg-slate-600"
                          }`}
                        ></div>
                        <div
                          className={`absolute top-0.5 bg-white w-5 h-5 rounded-full shadow transition-transform ${
                            preferences.functional ? "left-6" : "left-0.5"
                          }`}
                        ></div>
                      </button>
                    </div>
                  </div>
                </div>

                <div className="flex flex-col sm:flex-row gap-3">
                  <button
                    onClick={handleSaveCustom}
                    className="flex-1 px-6 py-3 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-600 transition-all duration-200 transform hover:scale-105 shadow-lg"
                  >
                    {isAr ? "حفظ التفضيلات" : "Save Preferences"}
                  </button>

                  <button
                    onClick={() => setShowCustomize(false)}
                    className="flex-1 px-6 py-3 border-2 border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-200 font-semibold rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"
                  >
                    {isAr ? "إلغاء" : "Cancel"}
                  </button>
                </div>

                <p className="text-xs text-slate-500 dark:text-slate-400 mt-4 text-center">
                  {isAr
                    ? "يمكنك تغيير تفضيلاتك في أي وقت في"
                    : "You can change your preferences anytime in our"}{" "}
                  <Link
                    href={`/${lang}/cookies`}
                    className="text-brand-green hover:underline font-medium"
                  >
                    {isAr ? "سياسة ملفات تعريف الارتباط" : "Cookie Policy"}
                  </Link>
                </p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Add animations */}
      <style jsx global>{`
        @keyframes fadeIn {
          from {
            opacity: 0;
          }
          to {
            opacity: 1;
          }
        }

        @keyframes slideUp {
          from {
            transform: translateY(100%);
            opacity: 0;
          }
          to {
            transform: translateY(0);
            opacity: 1;
          }
        }

        .animate-fadeIn {
          animation: fadeIn 0.3s ease-out;
        }

        .animate-slideUp {
          animation: slideUp 0.4s ease-out;
        }
      `}</style>
    </>
  );
}
