'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { Copy, Check, Sparkles, Star, ChevronLeft, ChevronRight } from 'lucide-react';
import { useFoodMartStore } from '@/store/foodmart';
import { toast } from '@/hooks/use-toast';
import { motion, AnimatePresence } from 'framer-motion';

interface BestsellerItem {
  id: string;
  name: string;
  price: number;
  discountPrice: number | null;
  rating: number;
  reviews: number;
  thumbnail: string;
  isHalal: boolean;
  category: { name: string };
}

interface HeroSectionProps {
  heroType?: string;
  // promo props
  promoLabel?: string;
  promoTitle1?: string;
  promoTitle2?: string;
  promoDesc?: string;
  promoCode?: string;
  // products props
  bestsellers?: BestsellerItem[];
  storeName?: string;
  whatsapp?: string;
}

function formatPrice(price: number): string {
  return new Intl.NumberFormat('id-ID').format(price);
}

export default function HeroSection({
  heroType = 'promo',
  promoLabel = '🎉 Special Offer',
  promoTitle1 = '20% OFF',
  promoTitle2 = 'Pesan Pertamamu!',
  promoDesc = 'Gunakan kode promo di checkout',
  promoCode = 'WELCOME20',
  bestsellers = [],
  storeName = 'FoodMart',
  whatsapp = '6281234567890',
}: HeroSectionProps) {
  const [copied, setCopied] = useState(false);
  const [currentSlide, setCurrentSlide] = useState(0);
  const selectedBranch = useFoodMartStore((s) => s.selectedBranch);
  const addToCart = useFoodMartStore((s) => s.addToCart);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(promoCode);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      const textArea = document.createElement('textarea');
      textArea.value = promoCode;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const handleQuickAdd = (food: BestsellerItem, e: React.MouseEvent) => {
    e.stopPropagation();
    addToCart({
      id: food.id,
      name: food.name,
      price: food.discountPrice || food.price,
      thumbnail: food.thumbnail,
      quantity: 1,
      variant: 'Regular',
      note: '',
    });
    toast({
      title: 'Ditambahkan!',
      description: `${food.name} masuk ke keranjang`,
    });
  };

  // Auto-slide for products mode
  useEffect(() => {
    if (heroType !== 'products' || bestsellers.length <= 1) return;
    const timer = setInterval(() => {
      setCurrentSlide((prev) => (prev + 1) % bestsellers.length);
    }, 3000);
    return () => clearInterval(timer);
  }, [heroType, bestsellers.length]);

  if (heroType === 'products' && bestsellers.length > 0) {
    return (
      <section className="relative overflow-hidden">
        <div className="relative mx-auto max-w-7xl px-4 py-8 sm:px-6 sm:py-12 lg:px-8 lg:py-16">
          <div className="relative rounded-2xl overflow-hidden bg-gradient-to-br from-[var(--accent-500)] via-[var(--accent-600)] to-[var(--accent-400)] p-6 sm:p-8 md:p-10 lg:p-12">
            {/* Decorative elements */}
            <div className="absolute top-0 right-0 h-64 w-64 rounded-full bg-white/10 blur-3xl -translate-y-1/2 translate-x-1/4" />
            <div className="absolute bottom-0 left-0 h-48 w-48 rounded-full bg-white/10 blur-2xl translate-y-1/2 -translate-x-1/4" />

            <div className="relative z-10">
              {/* Mobile: Vertical layout */}
              <div className="flex flex-col gap-8 lg:flex-row lg:items-center lg:justify-between lg:gap-12">
                {/* Left: Text */}
                <div className="flex-shrink-0 lg:max-w-md">
                  <div className="mb-3 inline-flex items-center gap-2 rounded-full bg-white/20 px-4 py-1.5 text-sm font-medium text-white backdrop-blur-sm">
                    <Sparkles className="h-4 w-4" />
                    ⭐ Menu Unggulan Kami
                  </div>
                  <h1 className="mb-3 text-2xl font-extrabold tracking-tight text-white sm:text-3xl md:text-4xl">
                    Cita Rasa Terbaik, <span className="block">Diantar ke Pintu Anda!</span>
                  </h1>
                  <p className="mb-6 text-base text-white/80 sm:text-lg">
                    Pilihan menu favorit pelanggan {storeName} yang paling laris dan lezat.
                  </p>
                  <a
                    href={`https://wa.me/${whatsapp}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 rounded-xl bg-white px-6 py-3 text-sm font-semibold text-[var(--accent-600)] shadow-lg transition-all hover:shadow-xl hover:bg-white/90 active:scale-95"
                  >
                    Pesan Sekarang
                  </a>
                </div>

                {/* Right: Product Carousel */}
                <div className="relative w-full lg:w-auto">
                  <div className="flex gap-3 overflow-x-auto pb-2 lg:overflow-visible lg:pb-0" style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}>
                    {bestsellers.map((food, i) => (
                      <motion.div
                        key={food.id}
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: i * 0.1 }}
                        className="shrink-0 w-44 sm:w-48 lg:w-44"
                      >
                        <div className="overflow-hidden rounded-xl bg-white/95 shadow-lg backdrop-blur-sm">
                          <div className="relative aspect-square overflow-hidden bg-white/20">
                            {food.thumbnail ? (
                              <img src={food.thumbnail} alt={food.name} className="h-full w-full object-cover" />
                            ) : (
                              <div className="flex h-full w-full items-center justify-center text-4xl">🍽️</div>
                            )}
                            {food.isHalal && (
                              <div className="absolute top-1.5 left-1.5 flex items-center gap-0.5 rounded-full bg-emerald-600/90 px-1.5 py-0.5 text-[8px] font-semibold text-white">
                                Halal
                              </div>
                            )}
                          </div>
                          <div className="p-3">
                            <p className="mb-1 line-clamp-1 text-xs font-semibold text-gray-900">{food.name}</p>
                            <div className="mb-1 flex items-center gap-1">
                              <Star className="h-3 w-3 fill-amber-500 text-amber-500" />
                              <span className="text-[10px] font-medium text-gray-600">{food.rating}</span>
                              <span className="text-[10px] text-gray-400">({food.reviews})</span>
                            </div>
                            <p className="mb-2 text-sm font-bold text-[var(--accent-600)]">
                              Rp {formatPrice(food.discountPrice || food.price)}
                            </p>
                            <button
                              onClick={(e) => handleQuickAdd(food, e)}
                              className="w-full rounded-lg bg-[var(--accent-500)] py-1.5 text-xs font-semibold text-white transition-all hover:bg-[var(--accent-600)] active:scale-95"
                            >
                              + Pesan
                            </button>
                          </div>
                        </div>
                      </motion.div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  // Default: Promo mode
  return (
    <section className="relative overflow-hidden">
      <div className="relative mx-auto max-w-7xl px-4 py-8 sm:px-6 sm:py-12 lg:px-8 lg:py-16">
        <div className="relative rounded-2xl overflow-hidden bg-gradient-to-br from-[var(--accent-500)] via-[var(--accent-600)] to-[var(--accent-400)] p-6 sm:p-8 md:p-10 lg:p-12">
          {/* Decorative elements */}
          <div className="absolute top-0 right-0 h-64 w-64 rounded-full bg-white/10 blur-3xl -translate-y-1/2 translate-x-1/4" />
          <div className="absolute bottom-0 left-0 h-48 w-48 rounded-full bg-amber-300/20 blur-2xl translate-y-1/2 -translate-x-1/4" />
          <div className="absolute top-1/2 right-1/4 h-32 w-32 rounded-full bg-white/5 blur-2xl" />

          {/* Floating food emojis */}
          <div className="absolute top-4 right-8 text-4xl sm:text-5xl opacity-30 animate-bounce" style={{ animationDuration: '3s' }}>
            🍕
          </div>
          <div className="absolute bottom-4 right-20 text-3xl sm:text-4xl opacity-20 animate-bounce" style={{ animationDuration: '4s', animationDelay: '1s' }}>
            🍔
          </div>
          <div className="absolute top-8 left-1/2 text-2xl sm:text-3xl opacity-20 animate-bounce" style={{ animationDuration: '3.5s', animationDelay: '0.5s' }}>
            🍟
          </div>

          <div className="relative z-10 max-w-lg">
            <div className="mb-3 inline-flex items-center gap-2 rounded-full bg-white/20 px-4 py-1.5 text-sm font-medium text-white backdrop-blur-sm">
              <Sparkles className="h-4 w-4" />
              {promoLabel}
            </div>
            <h1 className="mb-2 text-3xl font-extrabold tracking-tight text-white sm:text-4xl md:text-5xl">
              {promoTitle1}{' '}
              <span className="block sm:inline">{promoTitle2}</span>
            </h1>
            <p className="mb-6 text-base text-white/80 sm:text-lg">
              {promoDesc}
            </p>
            <div className="inline-flex items-center gap-3 rounded-xl bg-white/15 px-5 py-3 backdrop-blur-sm">
              <span className="text-sm font-medium text-white/70">Kode Promo:</span>
              <span className="rounded-lg bg-white px-4 py-1.5 text-lg font-bold text-[var(--accent-600)] tracking-wider">
                {promoCode}
              </span>
              <button
                onClick={handleCopy}
                className="flex items-center justify-center rounded-lg bg-white/20 p-2 text-white transition-all hover:bg-white/30"
                title="Salin kode"
              >
                {copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
