"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Zap, ShoppingBag, Clock } from "lucide-react";

import { products as staticProducts, promoEndsAt } from "@/lib/data";
import { fetchFlashSale } from "@/lib/api";
import { addToCart } from "@/lib/cart";

type SaleProduct = {
  id: string;
  name: string;
  price: number;
  salePrice: number;
  discount: number;
  image: string;
  colors: string[];
  sizes: string[];
  category: "featured" | "new" | "best";
  fabric: string[];
  description: string;
};

function buildFallbackProducts(): SaleProduct[] {
  return staticProducts.slice(0, 4).map((p, i) => {
    const discounts = [30, 25, 40, 20];
    const multipliers = [0.70, 0.75, 0.60, 0.80];
    return {
      ...p,
      discount: discounts[i],
      salePrice: Math.round(p.price * multipliers[i]),
    };
  });
}

/* ── Countdown hook ── */
function useCountdown(target: string) {
  const calc = () => {
    const diff = new Date(target).getTime() - Date.now();
    if (diff <= 0) return { d: 0, h: 0, m: 0, s: 0 };
    return {
      d: Math.floor(diff / 86_400_000),
      h: Math.floor((diff % 86_400_000) / 3_600_000),
      m: Math.floor((diff % 3_600_000) / 60_000),
      s: Math.floor((diff % 60_000) / 1_000),
    };
  };

  const [time, setTime] = useState(calc);

  useEffect(() => {
    const id = setInterval(() => setTime(calc()), 1000);
    return () => clearInterval(id);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [target]);

  return time;
}

/* ── Digit flip box ── */
function Digit({ value, label }: { value: number; label: string }) {
  const str = String(value).padStart(2, "0");
  return (
    <div className="flex flex-col items-center gap-1">
      <div
        className="relative flex h-14 w-14 items-center justify-center overflow-hidden rounded-xl text-2xl font-black tabular-nums sm:h-16 sm:w-16 sm:text-3xl"
        style={{
          background: "linear-gradient(170deg, rgba(201,162,80,0.18) 0%, rgba(201,162,80,0.06) 100%)",
          border: "1.5px solid rgba(201,162,80,0.35)",
          boxShadow: "0 0 20px rgba(201,162,80,0.15), inset 0 1px 0 rgba(255,255,255,0.07)",
          color: "#f0d080",
        }}
      >
        <AnimatePresence mode="wait">
          <motion.span
            key={str}
            initial={{ y: -20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 20, opacity: 0 }}
            transition={{ duration: 0.15 }}
          >
            {str}
          </motion.span>
        </AnimatePresence>
        {/* inner shine */}
        <div
          className="pointer-events-none absolute inset-x-0 top-0 h-1/2 rounded-t-xl"
          style={{ background: "linear-gradient(180deg, rgba(255,255,255,0.06) 0%, transparent 100%)" }}
        />
      </div>
      <span className="text-[10px] font-bold uppercase tracking-widest text-white/35">{label}</span>
    </div>
  );
}

/* ── Product card ── */
function SaleCard({
  product,
}: {
  product: SaleProduct;
}) {
  const [added, setAdded] = useState(false);

  const handleAdd = () => {
    addToCart(
      { ...product, price: product.salePrice },
      { color: product.colors[0], size: product.sizes[0] },
    );
    setAdded(true);
    setTimeout(() => setAdded(false), 1800);
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 24 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, amount: 0.15 }}
      whileHover={{ y: -5 }}
      transition={{ duration: 0.4, ease: "easeOut" }}
      className="group relative overflow-hidden rounded-2xl"
      style={{
        background: "linear-gradient(135deg, rgba(18,14,40,0.90) 0%, rgba(10,8,26,0.95) 100%)",
        border: "1px solid rgba(201,162,80,0.15)",
        boxShadow: "0 4px 24px rgba(0,0,0,0.45)",
      }}
    >
      {/* Discount badge */}
      <div
        className="absolute left-3 top-3 z-10 rounded-full px-2.5 py-1 text-[11px] font-black text-white"
        style={{ background: "linear-gradient(90deg,#ef4444,#dc2626)", boxShadow: "0 2px 12px rgba(239,68,68,0.45)" }}
      >
        -{product.discount}%
      </div>

      {/* Image */}
      <Link href={`/product/${product.id}`} className="block overflow-hidden">
        <div className="relative aspect-[3/4] w-full overflow-hidden">
          <Image
            src={product.image}
            alt={product.name}
            fill
            className="object-cover transition-transform duration-700 group-hover:scale-110"
            sizes="(max-width: 640px) 50vw, 25vw"
          />
          <div
            className="absolute inset-0"
            style={{ background: "linear-gradient(180deg, transparent 55%, rgba(4,4,16,0.88) 100%)" }}
          />
        </div>
      </Link>

      {/* Info */}
      <div className="p-4">
        <Link href={`/product/${product.id}`}>
          <h3 className="truncate text-sm font-bold text-white/85 transition-colors group-hover:text-amber-300">
            {product.name}
          </h3>
        </Link>
        <div className="mt-1.5 flex items-center gap-2">
          <span
            className="text-base font-extrabold"
            style={{
              background: "linear-gradient(90deg,#c9a250,#f0d080)",
              WebkitBackgroundClip: "text",
              backgroundClip: "text",
              WebkitTextFillColor: "transparent",
            }}
          >
            ৳{product.salePrice.toLocaleString()}
          </span>
          <span className="text-xs font-semibold text-white/30 line-through">
            ৳{product.price.toLocaleString()}
          </span>
        </div>
        <button
          onClick={handleAdd}
          className="mt-3 flex w-full items-center justify-center gap-1.5 rounded-xl py-2 text-xs font-bold text-[#07071a] transition-all hover:scale-[1.02]"
          style={{
            background: added
              ? "linear-gradient(90deg,#22c55e,#16a34a)"
              : "linear-gradient(90deg,#c9a250,#f0d080)",
          }}
        >
          <ShoppingBag className="h-3.5 w-3.5" />
          {added ? "কার্টে যোগ হয়েছে ✓" : "কার্টে যোগ করুন"}
        </button>
      </div>
    </motion.div>
  );
}

/* ── MAIN EXPORT ── */
export function FlashSale() {
  const [saleProducts, setSaleProducts] = useState<SaleProduct[]>(buildFallbackProducts());
  const [endTime, setEndTime] = useState(promoEndsAt);

  useEffect(() => {
    fetchFlashSale().then((data) => {
      if (data && Array.isArray(data.products) && data.products.length > 0) {
        const mapped: SaleProduct[] = data.products.map((p: {
          id: string; name: string; price: number; sale_price?: number | null;
          image: string; colors?: string[]; sizes?: string[]; category?: string;
          fabric?: string[]; description?: string;
        }) => {
          const base = p.price;
          const sale = p.sale_price ?? Math.round(base * 0.75);
          const disc = Math.round(((base - sale) / base) * 100);
          return {
            id: p.id,
            name: p.name,
            price: base,
            salePrice: sale,
            discount: disc,
            image: p.image,
            colors: p.colors ?? [],
            sizes: p.sizes ?? [],
            category: (p.category as "featured" | "new" | "best") ?? "featured",
            fabric: p.fabric ?? [],
            description: p.description ?? "",
          };
        });
        setSaleProducts(mapped.slice(0, 4));
      }
      if (data?.ends_at) setEndTime(data.ends_at);
    });
  }, []);

  const { d, h, m, s } = useCountdown(endTime);
  const expired = d === 0 && h === 0 && m === 0 && s === 0;

  return (
    <section
      className="relative overflow-hidden rounded-3xl"
      style={{
        background: "linear-gradient(135deg, rgba(12,8,30,0.98) 0%, rgba(7,7,26,1) 100%)",
        border: "1px solid rgba(201,162,80,0.14)",
        boxShadow: "0 8px 48px rgba(0,0,0,0.55)",
      }}
    >
      {/* Ambient glows */}
      <div className="pointer-events-none absolute -left-20 -top-20 h-72 w-72 rounded-full opacity-20" style={{ background: "radial-gradient(circle, rgba(239,68,68,0.5), transparent 70%)" }} />
      <div className="pointer-events-none absolute -right-16 bottom-0 h-64 w-64 rounded-full opacity-15" style={{ background: "radial-gradient(circle, rgba(201,162,80,0.6), transparent 70%)" }} />

      <div className="relative px-5 py-10 sm:px-8 sm:py-12">
        {/* Header */}
        <div className="flex flex-col items-center gap-3 text-center">
          <motion.div
            initial={{ scale: 0.8, opacity: 0 }}
            whileInView={{ scale: 1, opacity: 1 }}
            viewport={{ once: true }}
            className="flex items-center gap-2 rounded-full px-4 py-1.5 text-xs font-black uppercase tracking-widest text-white"
            style={{
              background: "linear-gradient(90deg, rgba(239,68,68,0.9), rgba(220,38,38,0.8))",
              boxShadow: "0 0 24px rgba(239,68,68,0.45)",
            }}
          >
            <Zap className="h-3.5 w-3.5 fill-white" />
            ফ্ল্যাশ সেল চলছে!
          </motion.div>

          <motion.h2
            initial={{ y: 16, opacity: 0 }}
            whileInView={{ y: 0, opacity: 1 }}
            viewport={{ once: true }}
            transition={{ delay: 0.1 }}
            className="text-3xl font-extrabold leading-tight sm:text-4xl"
            style={{
              background: "linear-gradient(90deg,#c9a250 0%,#f0d080 50%,#c9a250 100%)",
              WebkitBackgroundClip: "text",
              backgroundClip: "text",
              WebkitTextFillColor: "transparent",
            }}
          >
            সীমিত সময়ের অফার
          </motion.h2>
          <p className="max-w-sm text-sm text-white/45">
            নির্বাচিত পণ্যে ২০–৪০% ছাড়। অফার শেষ হওয়ার আগেই অর্ডার করুন।
          </p>
        </div>

        {/* Countdown */}
        <div className="mt-7 flex items-center justify-center gap-3">
          <Clock className="h-4 w-4 text-amber-400/60 shrink-0" />
          <div className="flex items-center gap-2">
            <Digit value={d} label="দিন" />
            <span className="mb-5 text-xl font-black text-amber-400/60">:</span>
            <Digit value={h} label="ঘণ্টা" />
            <span className="mb-5 text-xl font-black text-amber-400/60">:</span>
            <Digit value={m} label="মিনিট" />
            <span className="mb-5 text-xl font-black text-amber-400/60">:</span>
            <Digit value={s} label="সেকেন্ড" />
          </div>
        </div>

        {expired && (
          <p className="mt-3 text-center text-sm font-bold text-red-400">অফারের মেয়াদ শেষ হয়েছে।</p>
        )}

        {/* Product grid */}
        <div className="mt-10 grid gap-4 grid-cols-2 lg:grid-cols-4">
          {saleProducts.map((p) => (
            <SaleCard key={p.id} product={p} />
          ))}
        </div>

        {/* CTA */}
        <div className="mt-8 text-center">
          <Link
            href="/collections"
            className="inline-flex items-center gap-2 rounded-xl px-7 py-3 text-sm font-bold text-[#07071a] transition-all hover:scale-[1.04] hover:shadow-[0_0_28px_rgba(201,162,80,0.5)]"
            style={{ background: "linear-gradient(90deg,#c9a250,#f0d080,#c9a250)", backgroundSize: "200% 100%" }}
          >
            <ShoppingBag className="h-4 w-4" />
            সব পণ্য দেখুন
          </Link>
        </div>
      </div>
    </section>
  );
}
