import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { MapPin, Clock, Users, Star, ArrowRight, Calendar, Shield, Headphones, Award, Plane, CheckCircle2 } from "lucide-react";
import ToursSlider from "@/components/tours/ToursSlider";
import { db } from "@/lib/db";

export const metadata: Metadata = { title: "Tours & Travel - KC Systems" };

const fallbackFeatured = [
  { id: "bali-discovery", title: "Bali Discovery", destination: "Indonesia", duration: "5D/4N", price: "2490", tag: "Best Seller", image: "https://images.unsplash.com/photo-1537953773345-d172ccf13cf1?w=700&q=80" },
  { id: "istanbul-classic", title: "Istanbul Classic", destination: "Turkey", duration: "7D/6N", price: "4200", tag: "Featured", image: "https://images.unsplash.com/photo-1524231757912-21f4fe3a7200?w=700&q=80" },
  { id: "japan-sakura", title: "Japan Sakura Tour", destination: "Japan", duration: "8D/7N", price: "5800", tag: "Limited", image: "https://images.unsplash.com/photo-1528360983277-13d401cdc186?w=700&q=80" },
];

const fallbackPackages = [
  { id: "cameron-highlands", title: "Cameron Highlands Retreat", destination: "Malaysia", duration: "2D/1N", price: "390", image: "https://images.unsplash.com/photo-1596401040049-32d17e5e00d2?w=500&q=80", category: "Local" },
  { id: "langkawi-getaway", title: "Langkawi Beach Getaway", destination: "Malaysia", duration: "3D/2N", price: "780", image: "https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=500&q=80", category: "Local" },
  { id: "bangkok-explorer", title: "Bangkok Explorer", destination: "Thailand", duration: "4D/3N", price: "1650", image: "https://images.unsplash.com/photo-1555400038-63f5ba517a47?w=500&q=80", category: "Regional" },
  { id: "dubai-luxury", title: "Dubai Luxury Experience", destination: "UAE", duration: "6D/5N", price: "6500", image: "https://images.unsplash.com/photo-1512453979798-5ea266f8880c?w=500&q=80", category: "International" },
  { id: "mecca-umrah", title: "Umrah Package", destination: "Saudi Arabia", duration: "10D/9N", price: "4900", image: "https://images.unsplash.com/photo-1591604129939-f1efa4d9f7fa?w=500&q=80", category: "Religious" },
];

const fallbackSlides = [
  { id: "1", label: "Best Seller - Bali, Indonesia", title: "Discover the Island of Gods", desc: "Sacred temples, terraced rice fields, and pristine beaches.", image: "https://images.unsplash.com/photo-1537953773345-d172ccf13cf1?w=1600&q=80", price: "from $2,490" },
  { id: "2", label: "Most Popular - Turkey", title: "Istanbul: Where East Meets West", desc: "Walk between continents with iconic mosques and bazaars.", image: "https://images.unsplash.com/photo-1524231757912-21f4fe3a7200?w=1600&q=80", price: "from $4,200" },
  { id: "3", label: "Limited Seats - Japan", title: "Japan Sakura Cherry Blossom Tour", desc: "Cherry blossoms, shrines, ramen culture, and neon-lit streets.", image: "https://images.unsplash.com/photo-1528360983277-13d401cdc186?w=1600&q=80", price: "from $5,800" },
];

function usd(value: string | number) {
  const n = Number(value || 0);
  return `$${n.toLocaleString("en-US", { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
}

export default async function ToursPage() {
  const [dbPackages, dbSlides] = await Promise.all([
    db.tourPackage.findMany({
      where: { isActive: true },
      include: {
        category: true,
        images: { where: { isPrimary: true }, orderBy: { sortOrder: "asc" }, take: 1 },
      },
      orderBy: [{ isFeatured: "desc" }, { createdAt: "desc" }],
      take: 60,
    }),
    db.tourSlide.findMany({ where: { isActive: true }, orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }], take: 12 }),
  ]);

  const slides = dbSlides.length
    ? dbSlides.map((s) => ({
        id: s.id,
        label: s.subtitle || "Featured Tour",
        title: s.title || "Explore with KC Systems",
        desc: s.subtitle || "Curated local and international tour packages.",
        image: s.imageUrl,
        price: s.ctaText || "Book now",
      }))
    : fallbackSlides;

  const featuredPackages = dbPackages.filter((p) => p.isFeatured).slice(0, 3);
  const listPackages = dbPackages.slice(0, 12);

  const featured = featuredPackages.length
    ? featuredPackages.map((p) => ({
        id: p.slug || p.id,
        title: p.title,
        destination: p.destination || "Destination",
        duration: p.duration || "Flexible",
        price: p.pricePerPax.toString(),
        tag: "Featured",
        image: p.images[0]?.url || "https://images.unsplash.com/photo-1512453979798-5ea266f8880c?w=700&q=80",
      }))
    : fallbackFeatured;

  const packages = listPackages.length
    ? listPackages.map((p) => ({
        id: p.slug || p.id,
        title: p.title,
        destination: p.destination || "Destination",
        duration: p.duration || "Flexible",
        price: p.pricePerPax.toString(),
        category: p.category?.name || "Tour",
        image: p.images[0]?.url || "https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=500&q=80",
      }))
    : fallbackPackages;

  return (
    <div className="min-h-screen bg-neutral-50">
      <ToursSlider slides={slides} />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-20 pt-14 pb-24">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {[
            { icon: Shield, label: "100% Safe & Insured", sub: "All packages covered" },
            { icon: Headphones, label: "24/7 Travel Support", sub: "Always here for you" },
            { icon: Award, label: "Award-Winning Agency", sub: "Trusted since 2016" },
            { icon: CheckCircle2, label: "Best Price Guarantee", sub: "No hidden charges" },
          ].map(({ icon: Icon, label, sub }) => (
            <div key={label} className="bg-white border border-neutral-200 rounded-2xl p-5 flex items-center gap-4">
              <div className="w-10 h-10 bg-navy-50 rounded-xl flex items-center justify-center shrink-0">
                <Icon size={18} className="text-navy-600" />
              </div>
              <div>
                <div className="text-sm font-semibold text-navy-900">{label}</div>
                <div className="text-xs text-neutral-400">{sub}</div>
              </div>
            </div>
          ))}
        </div>

        <section>
          <div className="flex items-center justify-between mb-7">
            <div>
              <div className="inline-flex items-center gap-2 px-3 py-1 bg-navy-50 text-navy-700 text-xs font-semibold rounded-full mb-2 border border-navy-100">
                <Star size={11} /> Top Picks
              </div>
              <h2 className="text-2xl font-bold text-navy-900">Featured Tour Packages</h2>
              <p className="text-neutral-500 text-sm mt-0.5">Our most popular and highest-rated destinations</p>
            </div>
          </div>
          <div className="grid md:grid-cols-3 gap-6">
            {featured.map((t) => (
              <Link key={t.id} href={`/tours/${t.id}`} className="group bg-white border border-neutral-200 rounded-2xl overflow-hidden hover:shadow-xl transition-all">
                <div className="relative aspect-[4/3] overflow-hidden">
                  <Image src={t.image} alt={t.title} fill className="object-cover group-hover:scale-105 transition-transform duration-700" sizes="(max-width: 768px) 100vw, 33vw" unoptimized />
                  <div className="absolute inset-0 bg-gradient-to-t from-navy-900/70 to-transparent" />
                  <span className="absolute top-3 left-3 px-2.5 py-1 text-xs font-bold rounded-full bg-white/90 text-navy-800">{t.tag}</span>
                  <div className="absolute bottom-3 left-3 text-white">
                    <div className="text-xs text-white/70 flex items-center gap-1"><MapPin size={11} /> {t.destination}</div>
                    <div className="text-2xl font-bold">{usd(t.price)}</div>
                  </div>
                </div>
                <div className="p-5">
                  <h3 className="font-semibold text-navy-800 text-lg mb-3 group-hover:text-navy-600">{t.title}</h3>
                  <div className="flex items-center gap-4 text-xs text-neutral-500 border-t border-neutral-100 pt-3">
                    <span className="flex items-center gap-1"><Clock size={11} /> {t.duration}</span>
                    <span className="flex items-center gap-1"><Users size={11} /> Curated Package</span>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </section>

        <section>
          <div className="flex items-center justify-between mb-7">
            <div>
              <div className="inline-flex items-center gap-2 px-3 py-1 bg-gold-50 text-gold-700 text-xs font-semibold rounded-full mb-2 border border-gold-100">
                <Plane size={11} /> Destinations
              </div>
              <h2 className="text-2xl font-bold text-navy-900">All Tour Packages</h2>
              <p className="text-neutral-500 text-sm mt-0.5">Browse all active packages from admin panel</p>
            </div>
            <Link href="/tours" className="text-sm text-navy-700 hover:text-navy-900 font-medium flex items-center gap-1">
              Refresh <ArrowRight size={14} />
            </Link>
          </div>
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
            {packages.map((t) => (
              <Link key={t.id} href={`/tours/${t.id}`} className="group bg-white border border-neutral-200 rounded-2xl overflow-hidden hover:shadow-lg transition-all flex flex-col">
                <div className="relative aspect-video overflow-hidden">
                  <Image src={t.image} alt={t.title} fill className="object-cover group-hover:scale-105 transition-transform duration-700" sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw" unoptimized />
                </div>
                <div className="p-4 flex flex-col flex-1">
                  <h3 className="font-semibold text-navy-800 text-sm leading-snug group-hover:text-navy-600 mb-1">{t.title}</h3>
                  <p className="text-xs text-neutral-400 flex items-center gap-1 mb-3"><MapPin size={10} /> {t.destination} · {t.duration}</p>
                  <div className="flex items-center justify-between mt-auto">
                    <span className="font-bold text-navy-800">{usd(t.price)} <span className="text-xs text-neutral-400 font-normal">/pax</span></span>
                    <span className="text-xs px-2 py-0.5 rounded-full bg-neutral-100 text-neutral-600">{t.category}</span>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </section>

        <section className="relative overflow-hidden rounded-3xl">
          <div className="absolute inset-0">
            <Image
              src="https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=1400&q=80"
              alt="Road trip adventure"
              fill
              className="object-cover"
              sizes="100vw"
              unoptimized
            />
            <div className="absolute inset-0 bg-gradient-to-r from-navy-900/95 via-navy-900/80 to-navy-900/40" />
          </div>
          <div className="relative z-10 p-12 md:p-16 max-w-xl">
            <div className="inline-flex items-center gap-2 px-3 py-1 bg-gold-500/20 text-gold-300 text-xs font-semibold rounded-full mb-5 border border-gold-500/30">
              <Calendar size={11} /> Tailor-Made for You
            </div>
            <h2 className="text-3xl md:text-4xl font-bold text-white leading-tight mb-4">Need a custom trip plan?</h2>
            <p className="text-navy-200 text-sm leading-relaxed mb-6">Our team can customize itinerary, flights, hotels, visa, and tours based on your budget and dates.</p>
            <div className="flex flex-wrap gap-3">
              <Link href="/contact" className="inline-flex items-center gap-2 px-6 py-3 bg-gold-500 text-white font-semibold text-sm rounded-xl hover:bg-gold-400 transition-colors">
                Plan My Trip <ArrowRight size={15} />
              </Link>
              <Link href="/tours" className="inline-flex items-center gap-2 px-6 py-3 bg-white/10 text-white font-medium text-sm rounded-xl hover:bg-white/20 border border-white/20 transition-colors">
                Browse All Tours
              </Link>
            </div>
          </div>
        </section>
      </div>
    </div>
  );
}
