'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import {
  Flame,
  Clock,
  Zap,
  ShoppingBag,
  Sparkles,
  ChevronRight,
  TrendingUp,
  Percent,
} from 'lucide-react';
import { useDispatch } from 'react-redux';
import { addToCart } from '@/store/cartSlice';
import { showToast } from '@/components/common/Toast';
import api from '@/lib/api';

interface FlashDeal {
  id: string;
  bookId: string;
  title: string;
  slug: string;
  authorName: string;
  coverImage?: string | null;
  dealPrice: number;
  originalPrice: number;
  discountPercentage: number;
  badgeText: string;
  remainingMilliseconds: number;
  stockRemaining: number;
  stockLimit: number;
  claimedPercentage: number;
}

export function FlashDealsSection() {
  const dispatch = useDispatch();
  const [deals, setDeals] = useState<FlashDeal[]>([]);
  const [timeLeft, setTimeLeft] = useState<{ hours: number; minutes: number; seconds: number }>({
    hours: 18,
    minutes: 45,
    seconds: 0,
  });

  useEffect(() => {
    api.get('/smart-sales/flash-deals')
      .then((res) => {
        if (res.data?.data?.deals) {
          setDeals(res.data.data.deals);
        }
      })
      .catch(() => {});
  }, []);

  // Countdown timer ticker
  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev.seconds > 0) {
          return { ...prev, seconds: prev.seconds - 1 };
        } else if (prev.minutes > 0) {
          return { ...prev, minutes: prev.minutes - 1, seconds: 59 };
        } else if (prev.hours > 0) {
          return { hours: prev.hours - 1, minutes: 59, seconds: 59 };
        }
        return prev;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  const handleAddDealToCart = (deal: FlashDeal) => {
    dispatch(
      addToCart({
        id: deal.bookId,
        bookId: deal.bookId,
        title: deal.title,
        price: deal.originalPrice,
        discountPrice: deal.dealPrice,
        coverImage: deal.coverImage || undefined,
        stock: deal.stockRemaining,
        authorName: deal.authorName,
        quantity: 1,
      })
    );
    showToast(`Claimed Lightning Deal: “${deal.title}” added to cart!`, 'success');
  };

  if (deals.length === 0) return null;

  return (
    <section className="my-12 max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-8">
      <div className="bg-gradient-to-r from-red-950 via-rose-950 to-amber-950 rounded-3xl p-6 sm:p-8 text-white border border-rose-800/40 shadow-2xl space-y-6">
        {/* Header with Live Ticking Timer */}
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-rose-800/50 pb-6">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-2xl bg-gradient-to-tr from-amber-500 to-rose-600 flex items-center justify-center text-white shadow-lg shadow-rose-900/50 animate-pulse">
              <Flame className="w-7 h-7" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-xl sm:text-2xl font-black tracking-tight">
                  Lightning Flash Deals
                </h2>
                <span className="px-2.5 py-0.5 rounded-full bg-rose-500 text-white font-extrabold text-[10px] uppercase tracking-wider animate-pulse">
                  Live
                </span>
              </div>
              <p className="text-xs text-rose-200/80 mt-0.5">
                Steep limited-quantity promotional pricing on selected sacred texts & master commentaries
              </p>
            </div>
          </div>

          {/* Countdown Clock Box */}
          <div className="flex items-center gap-2 bg-black/40 backdrop-blur-md px-4 py-2 rounded-2xl border border-white/10 shrink-0">
            <Clock className="w-4 h-4 text-amber-400" />
            <span className="text-xs font-bold text-rose-200">Deals Expire In:</span>
            <div className="flex items-center gap-1 font-mono font-black text-sm text-amber-300">
              <span className="px-2 py-1 rounded-lg bg-white/10">
                {String(timeLeft.hours).padStart(2, '0')}
              </span>
              <span>:</span>
              <span className="px-2 py-1 rounded-lg bg-white/10">
                {String(timeLeft.minutes).padStart(2, '0')}
              </span>
              <span>:</span>
              <span className="px-2 py-1 rounded-lg bg-white/10">
                {String(timeLeft.seconds).padStart(2, '0')}
              </span>
            </div>
          </div>
        </div>

        {/* Deals Cards Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-6">
          {deals.map((deal) => (
            <div
              key={deal.id}
              className="p-5 rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 hover:border-rose-500/60 transition-all flex flex-col sm:flex-row gap-4 items-center justify-between"
            >
              <div className="w-24 h-32 rounded-xl bg-zinc-800 overflow-hidden shrink-0 shadow-md">
                {deal.coverImage ? (
                  <img src={deal.coverImage} alt={deal.title} className="w-full h-full object-cover" />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-zinc-500 text-xs">
                    Cover
                  </div>
                )}
              </div>

              <div className="flex-1 min-w-0 space-y-2 text-left w-full sm:w-auto">
                <span className="px-2 py-0.5 rounded-md bg-amber-500/20 text-amber-300 font-extrabold text-[10px] uppercase border border-amber-400/30">
                  {deal.badgeText}
                </span>
                <Link href={`/books/${deal.slug}`} className="block font-bold text-sm text-white hover:text-amber-300 line-clamp-1">
                  {deal.title}
                </Link>
                <p className="text-xs text-rose-200/70">{deal.authorName}</p>

                <div className="flex items-baseline gap-2">
                  <span className="text-lg font-black text-amber-400">₹{deal.dealPrice}</span>
                  <span className="text-xs text-zinc-400 line-through">₹{deal.originalPrice}</span>
                  <span className="text-xs font-extrabold text-emerald-400">
                    Save {deal.discountPercentage}%
                  </span>
                </div>

                {/* Claimed Stock Progress Bar */}
                <div className="space-y-1">
                  <div className="w-full h-2 rounded-full bg-white/10 overflow-hidden">
                    <div
                      className="h-full bg-gradient-to-r from-amber-400 to-rose-500 rounded-full"
                      style={{ width: `${deal.claimedPercentage}%` }}
                    />
                  </div>
                  <div className="flex justify-between text-[10px] text-rose-200/70 font-semibold">
                    <span>{deal.claimedPercentage}% Claimed</span>
                    <span className="text-amber-300 font-bold">{deal.stockRemaining} Copies Left</span>
                  </div>
                </div>
              </div>

              <button
                type="button"
                onClick={() => handleAddDealToCart(deal)}
                className="w-full sm:w-auto px-5 py-3 rounded-xl bg-gradient-to-r from-amber-500 to-rose-600 hover:from-amber-600 hover:to-rose-700 text-white font-extrabold text-xs shadow-lg transition-all flex items-center justify-center gap-1.5 shrink-0 cursor-pointer"
              >
                <Zap className="w-4 h-4" />
                <span>Claim Deal</span>
              </button>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
