'use client';
import { useState, useEffect, useCallback } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowRight, Truck, Shield, DollarSign, Star, Phone } from 'lucide-react';
import { VehicleCard } from '@/components/public/vehicle-card';
import { CounterAnimation } from '@/components/public/counter-animation';
import { useLanguage } from '@/lib/i18n/language-context';

const heroImages = [
  { src: '/images/hero-sleeper.jpg', alt: 'Sleeper truck - Evo Truck Sales' },
  { src: '/images/hero-daycab.jpg', alt: 'Day cab truck - Evo Truck Sales' },
  { src: '/images/hero-fleet.jpg', alt: 'Commercial truck fleet - Evo Truck Sales' },
];

const defaultCategories = [
  { name: 'Camiones', slug: 'camiones', imageUrl: '/images/cat-trucks.jpg' },
  { name: 'Retroexcavadoras', slug: 'retroexcavadoras', imageUrl: '/images/cat-excavators.jpg' },
  { name: 'Dump Trucks', slug: 'dump-trucks', imageUrl: '/images/cat-dump.jpg' },
  { name: 'Carros', slug: 'carros', imageUrl: '/images/cat-cars.jpg' },
];

function getCategoryDisplayName(cat: any, locale: string) {
  if (locale === 'en' && cat?.nameEn) return cat.nameEn;
  return cat?.name ?? '';
}

function HeroSlideshow() {
  const [current, setCurrent] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrent((prev) => (prev + 1) % heroImages.length);
    }, 5000);
    return () => clearInterval(timer);
  }, []);

  return (
    <div className="absolute inset-0">
      {heroImages.map((img, i) => (
        <div
          key={img.src}
          className="absolute inset-0 transition-opacity duration-1000"
          style={{ opacity: i === current ? 1 : 0 }}
        >
          <Image
            src={img.src}
            alt={img.alt}
            fill
            className="object-cover"
            priority={i === 0}
          />
        </div>
      ))}
      <div className="absolute inset-0 bg-gradient-to-r from-black/80 via-black/60 to-transparent" />
      {/* Slide indicators */}
      <div className="absolute bottom-6 left-1/2 -translate-x-1/2 flex gap-2 z-20">
        {heroImages.map((_, i) => (
          <button
            key={i}
            onClick={() => setCurrent(i)}
            className={`w-2.5 h-2.5 rounded-full transition-all ${i === current ? 'bg-red-500 w-8' : 'bg-white/50 hover:bg-white/80'}`}
          />
        ))}
      </div>
    </div>
  );
}

export function HomeClient({ featuredVehicles = [], categories = [], stats = { totalVehicles: 0, totalSold: 0 } }: any) {
  const displayCategories = (categories?.length ?? 0) > 0 ? categories.filter((c: any) => !c?.parentId) : defaultCategories;
  const { t, locale } = useLanguage();

  return (
    <div>
      {/* Hero Section with Image Slideshow */}
      <section className="relative h-[600px] md:h-[700px] overflow-hidden">
        <HeroSlideshow />
        <div className="relative z-10 max-w-[1200px] mx-auto px-4 h-full flex items-center">
          <motion.div initial={{ opacity: 0, x: -40 }} animate={{ opacity: 1, x: 0 }} transition={{ duration: 0.7 }} className="max-w-xl">
            <h1 className="font-display text-4xl md:text-5xl lg:text-6xl font-bold text-white tracking-tight leading-tight">
              {t.home.heroTitle} <span className="text-red-500">{t.home.heroHighlight}</span>
            </h1>
            <p className="mt-4 text-lg text-gray-300 leading-relaxed">
              {t.home.heroDesc}
            </p>
            <div className="mt-8 flex flex-wrap gap-4">
              <Link href="/inventory" className="bg-red-600 hover:bg-red-700 text-white px-8 py-3.5 rounded-lg font-semibold text-sm transition shadow-lg hover:shadow-xl flex items-center gap-2">
                {t.home.viewInventory} <ArrowRight className="w-4 h-4" />
              </Link>
              <a href="tel:9085909802" className="bg-white/10 backdrop-blur-sm hover:bg-white/20 text-white px-8 py-3.5 rounded-lg font-semibold text-sm transition border border-white/20 flex items-center gap-2">
                <Phone className="w-4 h-4" /> {t.home.callUs}
              </a>
            </div>
          </motion.div>
        </div>
      </section>

      {/* Stats bar */}
      <section className="bg-[#1a1a1a] py-6">
        <div className="max-w-[1200px] mx-auto px-4 grid grid-cols-2 md:grid-cols-4 gap-6 text-center">
          {[
            { label: t.home.statsAvailable, value: stats?.totalVehicles ?? 0, suffix: '+' },
            { label: t.home.statsSold, value: stats?.totalSold ?? 0, suffix: '+' },
            { label: t.home.statsExperience, value: 10, suffix: '+' },
            { label: t.home.statsClients, value: 500, suffix: '+' },
          ]?.map((stat: any, i: number) => (
            <div key={i}>
              <div className="text-2xl md:text-3xl font-bold text-red-500">
                <CounterAnimation end={stat?.value ?? 0} suffix={stat?.suffix ?? ''} />
              </div>
              <div className="text-gray-400 text-sm mt-1">{stat?.label ?? ''}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Featured Vehicles */}
      {(featuredVehicles?.length ?? 0) > 0 && (
        <section className="py-16 bg-[#faf5ef]">
          <div className="max-w-[1200px] mx-auto px-4">
            <motion.div initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} className="text-center mb-10">
              <h2 className="font-display text-3xl font-bold tracking-tight">{t.home.featuredTitle} <span className="text-red-600">{t.home.featuredHighlight}</span></h2>
              <p className="text-gray-500 mt-2">{t.home.featuredDesc}</p>
            </motion.div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {(featuredVehicles ?? [])?.map((v: any) => <VehicleCard key={v?.id} vehicle={v} />)}
            </div>
            <div className="text-center mt-8">
              <Link href="/inventory" className="inline-flex items-center gap-2 bg-red-600 hover:bg-red-700 text-white px-8 py-3 rounded-lg font-semibold text-sm transition">
                {t.home.viewAll} <ArrowRight className="w-4 h-4" />
              </Link>
            </div>
          </div>
        </section>
      )}

      {/* Categories */}
      <section className="py-16">
        <div className="max-w-[1200px] mx-auto px-4">
          <motion.div initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} className="text-center mb-10">
            <h2 className="font-display text-3xl font-bold tracking-tight">{t.home.categoriesTitle} <span className="text-red-600">{t.home.categoriesHighlight}</span></h2>
            <p className="text-gray-500 mt-2">{t.home.categoriesDesc}</p>
          </motion.div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            {(displayCategories ?? [])?.map((cat: any, i: number) => (
              <motion.div key={cat?.slug ?? i} initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ delay: i * 0.1 }}>
                <Link href={`/inventory?category=${cat?.slug ?? ''}`} className="group block">
                  <div className="relative aspect-[4/3] rounded-xl overflow-hidden shadow-md group-hover:shadow-xl transition">
                    <Image src={cat?.imageUrl ?? '/images/cat-trucks.jpg'} alt={getCategoryDisplayName(cat, locale)} fill className="object-cover group-hover:scale-110 transition-transform duration-500" />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent" />
                    <div className="absolute bottom-3 left-3 text-white">
                      <h3 className="font-semibold text-lg">{getCategoryDisplayName(cat, locale)}</h3>
                      {cat?._count?.vehicles != null && <p className="text-xs text-gray-300">{cat._count.vehicles} {t.home.available}</p>}
                    </div>
                  </div>
                </Link>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* Why Choose Us */}
      <section className="py-16 bg-[#1a1a1a] text-white">
        <div className="max-w-[1200px] mx-auto px-4">
          <motion.div initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} className="text-center mb-10">
            <h2 className="font-display text-3xl font-bold tracking-tight">{t.home.whyChooseTitle} <span className="text-red-500">{t.home.whyChooseHighlight}</span>?</h2>
          </motion.div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {[
              { icon: Truck, title: t.home.qualityEquip, desc: t.home.qualityDesc },
              { icon: DollarSign, title: t.home.flexFinancing, desc: t.home.flexFinancingDesc },
              { icon: Shield, title: t.home.warranty, desc: t.home.warrantyDesc },
              { icon: Star, title: t.home.exceptional, desc: t.home.exceptionalDesc },
            ]?.map((item: any, i: number) => (
              <motion.div key={i} initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ delay: i * 0.1 }} className="bg-white/5 backdrop-blur-sm p-6 rounded-xl border border-white/10 hover:border-red-500/50 transition">
                <item.icon className="w-10 h-10 text-red-500 mb-4" />
                <h3 className="font-semibold text-lg mb-2">{item?.title}</h3>
                <p className="text-gray-400 text-sm leading-relaxed">{item?.desc}</p>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="py-16 bg-red-600 text-white">
        <div className="max-w-[1200px] mx-auto px-4 text-center">
          <motion.div initial={{ opacity: 0, scale: 0.95 }} whileInView={{ opacity: 1, scale: 1 }} viewport={{ once: true }}>
            <h2 className="font-display text-3xl md:text-4xl font-bold tracking-tight">{t.home.ctaTitle}</h2>
            <p className="mt-3 text-red-100 text-lg">{t.home.ctaDesc}</p>
            <div className="mt-8 flex flex-wrap justify-center gap-4">
              <Link href="/contact" className="bg-white text-red-600 hover:bg-gray-100 px-8 py-3.5 rounded-lg font-semibold text-sm transition shadow-lg">
                {t.home.requestQuote}
              </Link>
              <a href="tel:9085909802" className="bg-red-700 hover:bg-red-800 text-white px-8 py-3.5 rounded-lg font-semibold text-sm transition border border-red-500 flex items-center gap-2">
                <Phone className="w-4 h-4" /> (908) 590-9802
              </a>
            </div>
          </motion.div>
        </div>
      </section>
    </div>
  );
}
