import { useState, useEffect, useCallback } from "react";
import { X, Zap, Percent, Clock } from "lucide-react";

interface Deal {
  name: string;
  discount: string;
  originalPrice: string;
  salePrice: string;
}

const dealSets: Deal[][] = [
  [
    { name: "Canva Pro Lifetime", discount: "94% OFF", originalPrice: "$125", salePrice: "$8" },
    { name: "Adobe Creative Cloud Pro Plus 1 Year", discount: "93% OFF", originalPrice: "$938", salePrice: "$62" },
    { name: "CapCut Pro 1 Month", discount: "63% OFF", originalPrice: "$16", salePrice: "$6" },
  ],
  [
    { name: "ChatGPT Plus 1 Month", discount: "49% OFF", originalPrice: "$37", salePrice: "$19" },
    { name: "Netflix Premium 1 Month", discount: "75% OFF", originalPrice: "$20", salePrice: "$5" },
    { name: "NordVPN 1 Year", discount: "72% OFF", originalPrice: "$180", salePrice: "$49" },
  ],
  [
    { name: "Spotify Premium 1 Year", discount: "80% OFF", originalPrice: "$180", salePrice: "$35" },
    { name: "YouTube Premium 1 Year", discount: "70% OFF", originalPrice: "$144", salePrice: "$42" },
    { name: "Microsoft 365 1 Year", discount: "78% OFF", originalPrice: "$150", salePrice: "$33" },
  ],
  [
    { name: "Midjourney Pro 1 Month", discount: "60% OFF", originalPrice: "$60", salePrice: "$24" },
    { name: "Disney+ Hotstar 1 Year", discount: "82% OFF", originalPrice: "$110", salePrice: "$20" },
    { name: "Figma Pro 1 Year", discount: "65% OFF", originalPrice: "$180", salePrice: "$62" },
  ],
  [
    { name: "GitHub Copilot 1 Year", discount: "55% OFF", originalPrice: "$240", salePrice: "$108" },
    { name: "LinkedIn Premium 1 Year", discount: "68% OFF", originalPrice: "$360", salePrice: "$115" },
    { name: "Perplexity Pro 1 Year", discount: "58% OFF", originalPrice: "$240", salePrice: "$99" },
  ],
];

function getWhatsAppLink(deal: Deal): string {
  const text = encodeURIComponent(
    `Hi! I want to order ${deal.name} from the Flash Sale.\n\nDiscount: ${deal.discount}\nOriginal Price: ${deal.originalPrice}\nSale Price: ${deal.salePrice}\n\nPlease help me proceed with the order.`
  );
  return `https://wa.me/917038146526?text=${text}`;
}

function getTimeLeft() {
  const now = new Date();
  const midnight = new Date(now);
  midnight.setHours(24, 0, 0, 0);
  const diff = midnight.getTime() - now.getTime();
  const h = Math.floor(diff / (1000 * 60 * 60));
  const m = Math.floor((diff / (1000 * 60)) % 60);
  const s = Math.floor((diff / 1000) % 60);
  return { h: String(h).padStart(2, "0"), m: String(m).padStart(2, "0"), s: String(s).padStart(2, "0") };
}

export default function FlashSalePopup() {
  const [visible, setVisible] = useState(false);
  const [dismissed, setDismissed] = useState(false);
  const [dealIndex, setDealIndex] = useState(0);
  const [timeLeft, setTimeLeft] = useState(getTimeLeft());

  // Countdown timer
  useEffect(() => {
    const timer = setInterval(() => setTimeLeft(getTimeLeft()), 1000);
    return () => clearInterval(timer);
  }, []);

  // Show popup after delay
  useEffect(() => {
    if (dismissed) return;
    const t = setTimeout(() => setVisible(true), 3000);
    return () => clearTimeout(t);
  }, [dismissed]);

  // Cycle deals periodically
  useEffect(() => {
    if (!visible || dismissed) return;
    const t = setInterval(() => {
      setDealIndex((prev) => (prev + 1) % dealSets.length);
    }, 8000);
    return () => clearInterval(t);
  }, [visible, dismissed]);

  const handleDismiss = useCallback(() => {
    setVisible(false);
    setDismissed(true);
  }, []);

  const handleDealClick = (deal: Deal) => {
    window.open(getWhatsAppLink(deal), "_blank", "noopener,noreferrer");
  };

  if (!visible || dismissed) return null;

  const currentDeals = dealSets[dealIndex];

  return (
    <div className="fixed bottom-4 left-4 sm:bottom-6 sm:left-6 z-50 animate-in slide-in-from-bottom-4 fade-in duration-500 max-w-[340px] sm:max-w-[360px] w-[calc(100vw-2rem)]">
      <div className="relative bg-[#141414] border border-[#ff8c42]/30 rounded-2xl shadow-2xl shadow-black/50 overflow-hidden">
        {/* Orange Header */}
        <div className="bg-gradient-to-r from-[#e8733c] to-[#ff8c42] px-4 py-3 sm:py-3.5 flex items-center justify-between relative">
          <div className="flex-1 text-center pr-8">
            <div className="flex items-center justify-center gap-1.5 sm:gap-2">
              <Zap className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-white" />
              <span className="text-[11px] sm:text-sm font-semibold text-white uppercase tracking-wider">
                Flash Sale Ends In:
              </span>
            </div>
            <div className="mt-0.5 sm:mt-1 flex items-center justify-center gap-1 text-white font-bold text-xl sm:text-2xl tracking-wider font-mono">
              <span>{timeLeft.h}</span>
              <span className="text-white/70">:</span>
              <span>{timeLeft.m}</span>
              <span className="text-white/70">:</span>
              <span>{timeLeft.s}</span>
            </div>
          </div>
          <button
            onClick={handleDismiss}
            className="absolute top-2.5 right-2.5 sm:top-3 sm:right-3 w-6 h-6 sm:w-7 sm:h-7 rounded-full bg-white/20 flex items-center justify-center hover:bg-white/30 transition-colors"
            aria-label="Close flash sale popup"
          >
            <X className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-white" />
          </button>
        </div>

        {/* Deal Items */}
        <div className="p-3 sm:p-4 space-y-2 sm:space-y-3">
          {currentDeals.map((deal, i) => (
            <button
              key={`${dealIndex}-${i}`}
              onClick={() => handleDealClick(deal)}
              className="flex items-center gap-2.5 sm:gap-3 p-2.5 sm:p-3 rounded-lg sm:rounded-xl bg-white/[0.03] border border-white/5 hover:border-[#ff8c42]/40 hover:bg-white/[0.06] transition-all w-full text-left cursor-pointer"
            >
              {/* Percentage Icon */}
              <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-md sm:rounded-lg bg-[#ff8c42]/15 flex items-center justify-center shrink-0">
                <Percent className="w-4 h-4 sm:w-5 sm:h-5 text-[#ff8c42]" />
              </div>
              {/* Deal Info */}
              <div className="flex-1 min-w-0">
                <p className="text-xs sm:text-sm font-medium text-white truncate leading-tight">
                  {deal.name}
                </p>
                <p className="text-[10px] sm:text-xs mt-0.5">
                  <span className="text-[#22c55e] font-semibold">{deal.discount}</span>
                  <span className="text-[#a5a5a5] line-through ml-1.5">{deal.originalPrice}</span>
                  <span className="text-[#22c55e] font-bold ml-1.5">{deal.salePrice}</span>
                </p>
              </div>
            </button>
          ))}

          {/* Urgency line */}
          <div className="flex items-center justify-center gap-1.5 py-0.5">
            <Clock className="w-3 h-3 text-[#ff6b6b]" />
            <span className="text-[10px] sm:text-[11px] text-[#ff6b6b] font-medium">
              Limited slots — Prices increase at midnight
            </span>
          </div>

          {/* CTA Button */}
          <a
            href="https://wa.me/917038146526?text=Hi! I want to order from the Flash Sale"
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center justify-center gap-2 w-full py-3 sm:py-3.5 text-xs sm:text-sm font-bold bg-[#25d366] text-white rounded-lg sm:rounded-xl hover:bg-[#20bd5a] transition-colors shadow-lg shadow-[#25d366]/20"
          >
            <MessageCircleIcon className="w-4 h-4 sm:w-5 sm:h-5" />
            Buy via WhatsApp
          </a>
        </div>
      </div>
    </div>
  );
}

function MessageCircleIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
    </svg>
  );
}
