import React, { useState, useEffect } from 'react';
import { Tag, Copy, Check, X, Sparkles } from 'lucide-react';
import { Coupon, subscribeToCoupons } from '../services/couponService';

export const TopPromoBar: React.FC = () => {
  const [activePromoCoupons, setActivePromoCoupons] = useState<Coupon[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [copiedCode, setCopiedCode] = useState<string | null>(null);
  const [isDismissed, setIsDismissed] = useState(false);

  useEffect(() => {
    const unsub = subscribeToCoupons((allCoupons) => {
      const todayStr = new Date().toISOString().split('T')[0];
      const featured = allCoupons.filter((c) => {
        if (c.status !== 'active') return false;
        if (c.showOnHome === false) return false;
        if (c.validUntil && todayStr > c.validUntil) return false;
        if (c.usageLimit !== null && c.usageLimit > 0 && c.totalUsed >= c.usageLimit) return false;
        return true;
      });
      setActivePromoCoupons(featured);
    });
    return () => unsub();
  }, []);

  // Auto-rotate promo messages if multiple exist
  useEffect(() => {
    if (activePromoCoupons.length <= 1) return;
    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % activePromoCoupons.length);
    }, 6000);
    return () => clearInterval(interval);
  }, [activePromoCoupons.length]);

  if (isDismissed || activePromoCoupons.length === 0) return null;

  const currentCoupon = activePromoCoupons[currentIndex] || activePromoCoupons[0];

  const handleCopyCode = (e: React.MouseEvent, code: string) => {
    e.stopPropagation();
    navigator.clipboard.writeText(code);
    setCopiedCode(code);
    setTimeout(() => setCopiedCode(null), 3000);
  };

  return (
    <div className="bg-gradient-to-r from-[#1C1814] via-[#2D1F18] to-[#1C1814] text-white border-b border-[#D4AF37]/30 py-2 px-4 relative z-40 text-xs font-sans shadow-md">
      <div className="max-w-7xl mx-auto flex items-center justify-between gap-2 sm:gap-4">
        
        {/* Left Side: Fire / Tag Icon + Announcement text */}
        <div className="flex items-center gap-2 overflow-hidden flex-1 justify-center sm:justify-start">
          <span className="hidden sm:inline-flex items-center justify-center p-1 bg-[#C81E3D]/30 border border-[#C81E3D]/50 rounded-lg text-[#FF859B] animate-pulse">
            <Sparkles className="w-3.5 h-3.5" />
          </span>

          <div className="flex items-center gap-2 truncate">
            <span className="bg-[#C81E3D] text-white text-[10px] font-extrabold uppercase px-2 py-0.5 rounded-full shrink-0">
              SPECIAL PROMO
            </span>

            <span className="text-amber-100 font-medium truncate">
              {currentCoupon.description || `Get ${currentCoupon.discountPercent}% OFF on your order!`}
            </span>
          </div>
        </div>

        {/* Right Side: Promo Code Badge & Copy Action */}
        <div className="flex items-center gap-2 shrink-0">
          <div className="flex items-center bg-black/50 border border-amber-500/40 rounded-lg p-0.5 pl-2 gap-2">
            <span className="font-mono font-extrabold text-[#D4AF37] tracking-wider text-xs">
              {currentCoupon.couponCode}
            </span>

            <button
              onClick={(e) => handleCopyCode(e, currentCoupon.couponCode)}
              className={`px-2.5 py-1 rounded-md font-bold text-[11px] transition-all flex items-center gap-1 cursor-pointer ${
                copiedCode === currentCoupon.couponCode
                  ? 'bg-emerald-600 text-white'
                  : 'bg-[#C81E3D] hover:bg-[#A6142E] text-white'
              }`}
            >
              {copiedCode === currentCoupon.couponCode ? (
                <>
                  <Check className="w-3 h-3" />
                  <span>COPIED!</span>
                </>
              ) : (
                <>
                  <Copy className="w-3 h-3" />
                  <span>COPY</span>
                </>
              )}
            </button>
          </div>

          <button
            onClick={() => setIsDismissed(true)}
            className="p-1 text-stone-400 hover:text-white rounded-md transition-colors cursor-pointer"
            title="Dismiss Announcement Bar"
          >
            <X className="w-3.5 h-3.5" />
          </button>
        </div>

      </div>
    </div>
  );
};
