import { useState, useEffect } from "react";
import { ShoppingCart, Heart, Star, Zap, Clock, Flame } from "lucide-react";
import { Link } from "react-router-dom";
import { toast } from "sonner";
import { useCartStore } from "@/stores/cartStore";

// Deal product - ماكينة قهوة بخصم 40%
const DEAL_PRODUCT = {
  id: "11",
  name: "ماكينة قهوة اسبريسو أوتوماتيكية",
  description: "ماكينة قهوة إيطالية الصنع بضغط 15 بار لإعداد قهوة اسبريسو احترافية في المنزل. مع خزان مياه سعة 1.8 لتر وطاحونة مدمجة.",
  price: 33000,
  originalPrice: 55000,
  image: "https://images.unsplash.com/photo-1495474472287-4d71bcdd2085?w=600&h=600&fit=crop",
  category: "مطبخ وطعام",
  categoryId: "kitchen",
  rating: 4.9,
  reviewCount: 321,
  inStock: true,
  isFeatured: true,
  unit: "جهاز",
  tags: [],
};

function getTimeUntilMidnight() {
  const now = new Date();
  const midnight = new Date();
  midnight.setHours(24, 0, 0, 0);
  const diff = Math.max(0, midnight.getTime() - now.getTime());
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  return { hours, minutes, seconds };
}

function CountdownUnit({ value, label }: { value: number; label: string }) {
  const [prev, setPrev] = useState(value);
  const [flip, setFlip] = useState(false);

  useEffect(() => {
    if (value !== prev) {
      setFlip(true);
      const t = setTimeout(() => {
        setPrev(value);
        setFlip(false);
      }, 200);
      return () => clearTimeout(t);
    }
  }, [value, prev]);

  return (
    <div className="flex flex-col items-center gap-1">
      <div
        className={`relative w-16 h-16 md:w-20 md:h-20 bg-white rounded-2xl shadow-lg flex items-center justify-center overflow-hidden transition-transform duration-200 ${
          flip ? "scale-95" : "scale-100"
        }`}
      >
        {/* Top half shine */}
        <div className="absolute inset-x-0 top-0 h-1/2 bg-white/20 rounded-t-2xl" />
        {/* Divider */}
        <div className="absolute inset-x-0 top-1/2 h-px bg-black/10" />
        <span className="text-2xl md:text-3xl font-black text-orange-600 tabular-nums">
          {String(value).padStart(2, "0")}
        </span>
      </div>
      <span className="text-xs font-bold text-white/80 uppercase tracking-wider">{label}</span>
    </div>
  );
}

export default function DealOfTheDay() {
  const [time, setTime] = useState(getTimeUntilMidnight());
  const { addToCart, toggleWishlist, isInWishlist } = useCartStore();
  const inWishlist = isInWishlist(DEAL_PRODUCT.id);

  useEffect(() => {
    const interval = setInterval(() => {
      setTime(getTimeUntilMidnight());
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  const discount = Math.round((1 - DEAL_PRODUCT.price / DEAL_PRODUCT.originalPrice) * 100);
  const savings = DEAL_PRODUCT.originalPrice - DEAL_PRODUCT.price;

  const handleAddToCart = () => {
    addToCart(DEAL_PRODUCT as never);
    toast.success(`تمت إضافة "${DEAL_PRODUCT.name}" إلى السلة`);
  };

  const handleToggleWishlist = () => {
    toggleWishlist(DEAL_PRODUCT as never);
    toast.success(inWishlist ? "تمت الإزالة من المفضلة" : "تمت الإضافة إلى المفضلة");
  };

  return (
    <section className="mt-12 rounded-3xl overflow-hidden bg-gradient-to-br from-red-600 via-rose-600 to-orange-500 shadow-2xl">
      <div className="relative">
        {/* Decorative blobs */}
        <div className="absolute -top-10 -right-10 w-52 h-52 bg-white/10 rounded-full blur-2xl" />
        <div className="absolute -bottom-10 -left-10 w-64 h-64 bg-black/10 rounded-full blur-2xl" />
        <div className="absolute top-1/2 left-1/3 w-32 h-32 bg-yellow-400/10 rounded-full blur-xl" />

        <div className="relative z-10 grid grid-cols-1 lg:grid-cols-2 gap-0">
          {/* Left: Info & Countdown */}
          <div className="p-8 md:p-10 flex flex-col justify-between">
            {/* Badge */}
            <div className="flex items-center gap-2 mb-6">
              <div className="flex items-center gap-1.5 bg-yellow-400 text-yellow-900 font-black text-sm px-4 py-1.5 rounded-full shadow-md">
                <Flame size={15} />
                عرض اليوم
              </div>
              <div className="flex items-center gap-1.5 bg-white/20 text-white text-sm font-bold px-3 py-1.5 rounded-full">
                <Zap size={14} />
                خصم {discount}%
              </div>
            </div>

            {/* Product name */}
            <div className="mb-6">
              <p className="text-white/70 text-sm font-semibold mb-1">{DEAL_PRODUCT.category}</p>
              <h2 className="text-2xl md:text-3xl font-black text-white leading-tight mb-3">
                {DEAL_PRODUCT.name}
              </h2>
              <p className="text-white/75 text-sm leading-relaxed line-clamp-2">
                {DEAL_PRODUCT.description}
              </p>
            </div>

            {/* Rating */}
            <div className="flex items-center gap-2 mb-5">
              <div className="flex">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Star
                    key={i}
                    size={14}
                    className={i < Math.floor(DEAL_PRODUCT.rating) ? "text-yellow-300" : "text-white/30"}
                    fill={i < Math.floor(DEAL_PRODUCT.rating) ? "currentColor" : "none"}
                  />
                ))}
              </div>
              <span className="text-yellow-300 font-bold text-sm">{DEAL_PRODUCT.rating}</span>
              <span className="text-white/60 text-xs">({DEAL_PRODUCT.reviewCount} تقييم)</span>
            </div>

            {/* Price */}
            <div className="mb-8">
              <div className="flex items-end gap-3 flex-wrap">
                <span className="text-4xl md:text-5xl font-black text-white">
                  {DEAL_PRODUCT.price.toLocaleString()}
                  <span className="text-xl mr-1">ر.ي</span>
                </span>
                <span className="text-white/50 line-through text-xl mb-1">
                  {DEAL_PRODUCT.originalPrice.toLocaleString()} ر.ي
                </span>
              </div>
              <div className="mt-2 inline-flex items-center gap-1.5 bg-green-400/20 border border-green-300/30 text-green-300 text-sm font-bold px-3 py-1 rounded-full">
                💰 وفر {savings.toLocaleString()} ر.ي
              </div>
            </div>

            {/* Countdown */}
            <div className="mb-8">
              <div className="flex items-center gap-2 text-white/80 text-sm font-semibold mb-3">
                <Clock size={16} />
                ينتهي العرض خلال
              </div>
              <div className="flex items-center gap-3">
                <CountdownUnit value={time.hours} label="ساعة" />
                <span className="text-white/60 text-3xl font-black mb-5">:</span>
                <CountdownUnit value={time.minutes} label="دقيقة" />
                <span className="text-white/60 text-3xl font-black mb-5">:</span>
                <CountdownUnit value={time.seconds} label="ثانية" />
              </div>
            </div>

            {/* Actions */}
            <div className="flex gap-3">
              <button
                onClick={handleAddToCart}
                className="flex-1 flex items-center justify-center gap-2 bg-white text-orange-600 font-black py-4 rounded-2xl hover:bg-yellow-50 transition-all duration-200 shadow-xl active:scale-95 text-base"
              >
                <ShoppingCart size={20} />
                أضف إلى السلة
              </button>
              <button
                onClick={handleToggleWishlist}
                className={`w-14 rounded-2xl flex items-center justify-center border-2 transition-all duration-200 ${
                  inWishlist
                    ? "bg-red-500 border-red-500 text-white"
                    : "bg-white/10 border-white/30 text-white hover:bg-white/20"
                }`}
              >
                <Heart size={20} fill={inWishlist ? "currentColor" : "none"} />
              </button>
              <Link
                to={`/products/${DEAL_PRODUCT.id}`}
                className="w-14 rounded-2xl flex items-center justify-center bg-white/10 border-2 border-white/30 text-white hover:bg-white/20 transition-all duration-200 text-sm font-bold"
              >
                ←
              </Link>
            </div>
          </div>

          {/* Right: Product Image */}
          <div className="relative flex items-center justify-center p-6 lg:p-0 lg:min-h-[420px]">
            {/* Glow behind image */}
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="w-64 h-64 bg-white/15 rounded-full blur-3xl" />
            </div>

            {/* Discount badge floating */}
            <div className="absolute top-6 right-6 w-20 h-20 bg-yellow-400 rounded-full flex flex-col items-center justify-center shadow-xl z-20 rotate-12">
              <span className="text-yellow-900 font-black text-lg leading-none">-{discount}%</span>
              <span className="text-yellow-900 text-xs font-bold">خصم</span>
            </div>

            <Link to={`/products/${DEAL_PRODUCT.id}`} className="relative z-10 block">
              <img
                src={DEAL_PRODUCT.image}
                alt={DEAL_PRODUCT.name}
                className="w-72 h-72 md:w-80 md:h-80 lg:w-full lg:h-full lg:max-w-sm lg:max-h-[380px] object-cover rounded-2xl shadow-2xl hover:scale-105 transition-transform duration-500"
              />
            </Link>

            {/* Stock urgency bar */}
            <div className="absolute bottom-6 left-6 right-6 z-20 lg:left-8 lg:right-8">
              <div className="bg-black/40 backdrop-blur-sm rounded-xl p-3">
                <div className="flex justify-between text-white text-xs font-bold mb-1.5">
                  <span>المتبقي من المخزون</span>
                  <span className="text-yellow-300">7 قطع فقط!</span>
                </div>
                <div className="h-2 bg-white/20 rounded-full overflow-hidden">
                  <div
                    className="h-full bg-gradient-to-r from-yellow-400 to-red-400 rounded-full animate-pulse"
                    style={{ width: "28%" }}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
