import Link from "next/link";
import { and, asc, desc, eq, sql, isNotNull, gt } from "drizzle-orm";
import { db } from "@/db";
import { products, slides, blogPosts } from "@/db/schema";
import { getCategories, getSettings, sellable } from "@/lib/data";
import { HeroSlider, Counter } from "@/components/store";
import { ProductGrid } from "@/components/ProductCard";
import { NewsletterForm } from "@/components/forms";

function Section({ title, href, children, sub }: { title: string; href?: string; sub?: string; children: React.ReactNode }) {
  return (
    <section className="container-x mt-16">
      <div className="flex items-end justify-between mb-6 gap-4">
        <div><h2 className="section-title">{title}</h2>{sub && <p className="text-slate-500 text-sm mt-1">{sub}</p>}</div>
        {href && <Link href={href} className="text-sm font-semibold text-brand hover:underline shrink-0">View all →</Link>}
      </div>
      {children}
    </section>
  );
}

export default async function Home() {
  const s = await getSettings();
  const cats = await getCategories();
  const q = (where: ReturnType<typeof and> | undefined, order = desc(products.createdAt), n = 8) => db.select().from(products).where(and(sellable, where)).orderBy(order).limit(n);
  const catId = (i: number) => cats[i]?.id ?? -1;
  const [hs, featured, best, newest, offers, baby, vit, posts] = await Promise.all([
    db.select().from(slides).where(eq(slides.active, true)).orderBy(asc(slides.sortOrder)),
    q(eq(products.featured, true)), q(eq(products.bestSeller, true)), q(undefined, desc(products.id)),
    q(and(isNotNull(products.comparePrice), gt(products.comparePrice, products.price))),
    q(eq(products.categoryId, catId(1)), desc(products.id), 4), q(eq(products.categoryId, catId(0)), desc(products.id), 4),
    db.select().from(blogPosts).where(eq(blogPosts.published, true)).orderBy(desc(blogPosts.createdAt)).limit(3),
  ]);
  const [{ n: productCount }] = await db.select({ n: sql<number>`count(*)::int` }).from(products).where(sellable);
  const sec = s.sections;
  return (
    <>
      <HeroSlider slides={hs} />
      <section className="container-x mt-6 grid grid-cols-2 lg:grid-cols-4 gap-3">
        {[["🚚", "Home Delivery", "Kalisizo & beyond"], ["💊", "Genuine Products", "Sourced responsibly"], ["👩‍⚕️", "Pharmacist Advice", "Talk to our team"], ["🔒", "Secure Payments", "Mobile money & cards"]].map(([i, t, d]) => (
          <div key={t} className="card p-4 flex items-center gap-3 reveal"><span className="text-2xl w-12 h-12 rounded-xl bg-mint grid place-items-center shrink-0">{i}</span><div><div className="font-bold text-sm">{t}</div><div className="text-xs text-slate-500">{d}</div></div></div>
        ))}
      </section>

      {sec.categories && (
        <Section title="Shop by Category" href="/categories" sub="Everything your family needs, beautifully organised.">
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-5">
            {cats.map((c) => (
              <Link key={c.id} href={`/category/${c.slug}`} className="group card overflow-hidden hover:-translate-y-1 hover:shadow-xl transition duration-300 reveal">
                <div className="aspect-[4/3] overflow-hidden bg-mint">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  {c.image ? <img src={c.image} alt={c.name} loading="lazy" className="w-full h-full object-cover group-hover:scale-110 transition duration-700" /> : null}
                </div>
                <div className="p-4"><div className="font-bold text-sm leading-tight min-h-[2.25rem]">{c.name}</div><span className="text-xs font-semibold text-brand mt-1 inline-block group-hover:translate-x-1 transition">Explore Category →</span></div>
              </Link>
            ))}
          </div>
        </Section>
      )}

      {sec.featured && <Section title="Featured Products" href="/shop?featured=1"><ProductGrid items={featured} /></Section>}

      <section className="container-x mt-16 grid md:grid-cols-2 gap-5">
        <div className="rounded-3xl bg-royal text-white p-8 md:p-10 relative overflow-hidden reveal">
          <div className="absolute -right-10 -bottom-10 w-48 h-48 rounded-full bg-white/10" />
          <span className="text-xs font-bold uppercase tracking-widest text-white/70">Prescription Service</span>
          <h3 className="text-2xl md:text-3xl font-extrabold mt-2">Upload your prescription</h3>
          <p className="text-white/80 mt-2 max-w-sm text-sm">Our licensed pharmacist reviews it and contacts you to arrange fulfilment.</p>
          <Link href="/prescription" className="btn bg-white text-royal mt-6">Upload Now →</Link>
        </div>
        <div className="rounded-3xl bg-brand text-white p-8 md:p-10 relative overflow-hidden reveal">
          <div className="absolute -right-10 -bottom-10 w-48 h-48 rounded-full bg-white/10" />
          <span className="text-xs font-bold uppercase tracking-widest text-white/70">Teleconsultation</span>
          <h3 className="text-2xl md:text-3xl font-extrabold mt-2">Talk to our healthcare team</h3>
          <p className="text-white/80 mt-2 max-w-sm text-sm">Book a convenient time for a remote consultation with an authorised professional.</p>
          <Link href="/consultation" className="btn bg-white text-brand mt-6">Book Consultation →</Link>
        </div>
      </section>

      {sec.bestSellers && <Section title="Best Sellers" href="/shop?best=1"><ProductGrid items={best} /></Section>}
      {sec.offers && offers.length > 0 && <Section title="Special Discounts" href="/shop?offers=1" sub="Limited-time savings on family favourites."><ProductGrid items={offers} /></Section>}
      {sec.newArrivals && <Section title="New Arrivals" href="/shop?sort=new"><ProductGrid items={newest} /></Section>}
      {sec.babyEssentials && baby.length > 0 && <Section title="Mother & Baby Essentials" href={`/category/${cats[1]?.slug}`}><ProductGrid items={baby} /></Section>}
      {sec.vitamins && vit.length > 0 && <Section title="Vitamins & Supplements" href={`/category/${cats[0]?.slug}`}><ProductGrid items={vit} /></Section>}

      {sec.services && (
        <section className="container-x mt-16">
          <div className="rounded-3xl bg-mint p-8 md:p-12 grid md:grid-cols-4 gap-6 text-center">
            {[[productCount, "+", "Products available"], [cats.length, "", "Health categories"], [7, " days", "Open every week"], [100, "%", "Pharmacist-reviewed Rx"]].map(([n, suf, l]) => (
              <div key={String(l)}><div className="text-4xl font-extrabold text-brand"><Counter to={Number(n)} suffix={String(suf)} /></div><div className="text-sm text-slate-600 mt-1">{l}</div></div>
            ))}
          </div>
        </section>
      )}

      {sec.blog && posts.length > 0 && (
        <Section title="Health & Wellness Blog" href="/blog">
          <div className="grid md:grid-cols-3 gap-5">
            {posts.map((p) => (
              <Link key={p.id} href={`/blog/${p.slug}`} className="card overflow-hidden group reveal">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                {p.image && <img src={p.image} alt={p.title} className="aspect-video w-full object-cover group-hover:scale-105 transition duration-500" />}
                <div className="p-5"><h3 className="font-bold group-hover:text-brand">{p.title}</h3><p className="text-sm text-slate-500 mt-1">{p.excerpt}</p></div>
              </Link>
            ))}
          </div>
        </Section>
      )}

      <section className="container-x mt-16">
        <div className="card p-8 md:p-10 flex flex-col md:flex-row items-center gap-6 justify-between bg-softblue border-0">
          <div><h3 className="text-xl font-extrabold">Stay healthy with our newsletter</h3><p className="text-sm text-slate-600">Health tips and exclusive offers. Unsubscribe anytime.</p></div>
          <NewsletterForm />
        </div>
      </section>
    </>
  );
}
