'use client';

import React, { useState, useEffect } from 'react';

interface Banner {
  id: number;
  text: string;
  discountCode: string;
  discountPercent: number;
  active: boolean;
  bgColor: string; // Can be hex (#000000), rgb (rgb(0,0,0)), or tailwind class (bg-red-600)
  textColor: string; // Can be hex (#ffffff), rgb (rgb(255,255,255)), or tailwind class (text-white)
  expiresAt: string | null;
}

const BANNER_COOKIE_NAME = 'banner_dismissed';
const BANNER_COOKIE_MAX_AGE = 7 * 24 * 60 * 60; // 7 days in seconds

const getBannerCookie = (): boolean => {
  if (typeof document === 'undefined') return false;
  const cookies = document.cookie.split(';');
  return cookies.some(cookie => cookie.trim().startsWith(`${BANNER_COOKIE_NAME}=`));
};

const setBannerCookie = () => {
  document.cookie = `${BANNER_COOKIE_NAME}=true; max-age=${BANNER_COOKIE_MAX_AGE}; path=/`;
};

const BannerSection: React.FC = () => {
  const [banners, setBanners] = useState<Banner[]>([]);
  const [loading, setLoading] = useState(true);
  const [isClosed, setIsClosed] = useState(false);
  const [copiedCode, setCopiedCode] = useState<number | null>(null);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  useEffect(() => {
    // Check if banner was already dismissed
    if (getBannerCookie()) {
      setIsClosed(true);
      setLoading(false);
      return;
    }

    // Fetch banners
    const fetchBanners = async () => {
      try {
        const response = await fetch('/data/banners.json');
        const data = await response.json();
        setBanners(data);
      } catch (error) {
        // Silently fail
      } finally {
        setLoading(false);
      }
    };

    fetchBanners();
  }, []);

  const handleCloseBanner = () => {
    setBannerCookie();
    setIsClosed(true);
  };

  const handleCopyCode = async (code: string, bannerId: number) => {
    try {
      // Try modern clipboard API first
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(code);
      } else {
        // Fallback for older browsers and mobile
        const textarea = document.createElement('textarea');
        textarea.value = code;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
      }

      setCopiedCode(bannerId);
      setToastMessage(`Kód "${code}" zkopírován! 🎉`);
      setShowToast(true);
      setTimeout(() => {
        setCopiedCode(null);
      }, 2000);
      setTimeout(() => {
        setShowToast(false);
      }, 3000);
    } catch (error) {
      setToastMessage('Chyba při kopírování');
      setShowToast(true);
      setTimeout(() => setShowToast(false), 3000);
    }
  };

  const isExpired = (expiresAt: string | null) => {
    if (!expiresAt) return false;
    return new Date() > new Date(expiresAt);
  };

  const activeBanners = banners.filter(
    banner => banner.active && !isExpired(banner.expiresAt)
  );

  if (loading || activeBanners.length === 0 || isClosed) {
    return null;
  }

  const banner = activeBanners[0];

  // Helper function to convert color values (hex, rgb, or tailwind) to usable CSS
  const getColorValue = (color: string): string => {
    // If it's already hex or rgb format, use it directly
    if (color.startsWith('#') || color.startsWith('rgb')) {
      return color;
    }

    // Tailwind color mappings
    const tailwindColors: { [key: string]: string } = {
      'bg-red-600': '#dc2626',
      'bg-luxury-gold': '#DDA20D',
      'bg-blue-600': '#2563eb',
      'bg-purple-600': '#9333ea',
      'bg-green-600': '#16a34a',
      'bg-black': '#000000',
      'text-white': '#ffffff',
      'text-luxury-dark': '#0a0a0a',
      'text-black': '#000000',
    };

    return tailwindColors[color] || '#000000';
  };

  return (
    <>
      {/* Toast Notification */}
      {showToast && (
        <div className="fixed bottom-8 left-1/2 -translate-x-1/2 z-50 animate-in fade-in slide-in-from-bottom-4 duration-300">
          <div className="bg-green-500 text-white px-6 py-4 rounded-lg shadow-2xl font-semibold text-center">
            {toastMessage}
          </div>
        </div>
      )}

      {/* Modal Overlay */}
      <div className="fixed inset-0 bg-black/50 z-40 flex items-center justify-center p-3 sm:p-4">
        {/* Modal Content */}
        <div
          style={{
            backgroundColor: getColorValue(banner.bgColor),
            color: getColorValue(banner.textColor),
          }}
          className="w-full max-w-lg max-h-[calc(100svh-1.5rem)] overflow-y-auto rounded-lg shadow-2xl p-5 sm:p-8 relative animate-in fade-in slide-in-from-bottom-4 duration-300"
        >
          {/* Close Button */}
          <button
            onClick={handleCloseBanner}
            className="absolute top-3 right-3 sm:top-4 sm:right-4 w-11 h-11 flex items-center justify-center hover:opacity-70 transition-opacity"
            aria-label="Zavřít"
          >
            <svg
              className="w-6 h-6"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>

          {/* Content */}
          <div className="space-y-4">
            <h2 className="pr-10 text-xl sm:text-2xl md:text-3xl font-bold font-aptos break-words">
              {banner.text}
            </h2>

            {banner.discountPercent > 0 && (
              <>
                <p className="text-base md:text-lg">
                  Slevu <span className="font-bold text-xl">{banner.discountPercent} %</span> získáte s kódem:
                </p>

                {/* Discount Code - Clickable to Copy */}
                <button
                  onClick={() => handleCopyCode(banner.discountCode, banner.id)}
                  className="w-full bg-white/20 hover:bg-white/30 rounded-lg p-4 text-center transition-colors duration-200 group"
                >
                  <p className="font-mono text-2xl sm:text-3xl font-bold tracking-wider sm:tracking-widest break-all group-hover:opacity-80">
                    {banner.discountCode}
                  </p>
                  <p className="text-xs uppercase tracking-wider mt-2 opacity-60 group-hover:opacity-100">
                    {copiedCode === banner.id ? '✓ Zkopírováno!' : 'Klikněte pro zkopírování'}
                  </p>
                </button>
              </>
            )}

            {/* Action Button */}
            <button
              onClick={handleCloseBanner}
              className="w-full bg-white text-black font-bold py-3 rounded-lg hover:bg-gray-100 transition-colors duration-200"
            >
              Rozumím
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

export default BannerSection;
