import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import { toProductDTO } from '@/lib/product';
import { getCurrentCustomer } from '@/lib/auth';
import { fetchActivePromotions } from '@/lib/promotions';
import ProductCard from '@/components/ProductCard';
import ProductMockup from '@/components/ProductMockup';
import CherryBlossom from '@/components/CherryBlossom';
import Reveal from '@/components/Reveal';

const REASSURANCES = [
  { label: 'Made to order', body: 'Printed after you check out — nothing sits pre-made on a shelf.' },
  { label: 'Ships from the UK', body: 'Every order goes out from us, start to finish.' },
  { label: 'Secure checkout', body: 'Payments handled securely via Stripe.' },
  { label: 'Questions?', body: 'sales@craft2prints.co.uk' },
];

export default async function HomePage() {
  const activePromotions = await fetchActivePromotions();

  const galleryPhotos = await prisma.galleryPhoto.findMany({
    take: 6,
    orderBy: { createdAt: 'desc' },
  });

  const products = await prisma.product.findMany({
    where: { showOnPersonalised: true },
    take: 4,
    orderBy: { createdAt: 'asc' },
  });
  const featured = products.map((p) => toProductDTO(p, activePromotions));

  const readyMadeRows = await prisma.product.findMany({
    where: { showOnProducts: true },
    take: 4,
    orderBy: { createdAt: 'asc' },
  });
  const readyMade = readyMadeRows.map((p) => toProductDTO(p, activePromotions));
  const readyMadeCount = readyMade.length;

  const categoryRows = await prisma.category.findMany({
    where: { showOnPersonalised: true },
    orderBy: { name: 'asc' },
  });
  const categories = categoryRows.map((c) => ({ label: c.name, value: c.slug }));

  const customer = await getCurrentCustomer();

  const steps = [
    {
      n: '01',
      title: 'Pick your product',
      body: 'Choose a ready-made favorite, or start from a template to design your own.',
    },
    {
      n: '02',
      title: 'Make it yours (if you want)',
      body: 'Personalising? Add your own text and images right on the product in our design tool. Buying ready-made? Skip straight to checkout.',
    },
    {
      n: '03',
      title: 'We print & ship',
      body: 'Personalised pieces are printed after you check out. Ready-made ships as-is — either way, it comes straight from us.',
    },
  ];

  return (
    <div>
      {/* Hero */}
      <section className="relative z-0 mx-auto max-w-6xl px-6 pb-14 pt-14 md:pt-20">
        {/* Decorative cherry blossoms — subtle, behind the content, ignored by screen readers/clicks */}
        <div className="pointer-events-none absolute inset-0 -z-10 overflow-hidden">
          <CherryBlossom size={26} className="animate-drift absolute left-[4%] top-6 opacity-20" style={{ '--drift-rotate': '-8deg' } as React.CSSProperties} />
          <CherryBlossom size={18} className="animate-drift absolute left-[42%] top-28 opacity-10" style={{ animationDelay: '2s', '--drift-rotate': '15deg' } as React.CSSProperties} />
          <CherryBlossom size={34} className="animate-drift absolute bottom-4 left-[12%] opacity-20" style={{ animationDelay: '1s', '--drift-rotate': '25deg' } as React.CSSProperties} />
          <CherryBlossom size={20} className="animate-drift absolute right-[32%] top-2 opacity-15" style={{ animationDelay: '3s', '--drift-rotate': '-20deg' } as React.CSSProperties} />
          <CherryBlossom size={28} className="animate-drift absolute bottom-10 right-[6%] opacity-20" style={{ animationDelay: '1.5s', '--drift-rotate': '10deg' } as React.CSSProperties} />
          <CherryBlossom size={16} className="animate-drift absolute right-[18%] top-1/2 opacity-10" style={{ animationDelay: '4s', '--drift-rotate': '-35deg' } as React.CSSProperties} />
        </div>

        <div className="grid items-center gap-12 md:grid-cols-2">
          <Reveal>
            <p className="font-script text-3xl text-splash-pink">Ink it. Print it. Love it.</p>
            <h1 className="mt-3 font-display text-5xl leading-[1.05] md:text-6xl">
              Design something only <span className="brand-gradient-text">you</span> would make.
            </h1>
            <p className="mt-5 max-w-md text-muted">
              Start from a template and make it your own — or shop pieces we&apos;ve already made.
              Either way, it ships from us.
            </p>
            <div className="mt-8 flex flex-wrap items-center gap-3">
              <Link
                href="/made-to-order"
                className="bg-clay px-7 py-3 text-sm font-medium text-paper transition-colors hover:bg-clay-dark"
              >
                Start designing
              </Link>
              <Link
                href="/products"
                className="border-2 border-ink px-7 py-3 text-sm font-medium text-ink transition-colors hover:border-clay hover:text-clay"
              >
                Shop ready-made
              </Link>
            </div>
          </Reveal>

          <Reveal delayMs={150} className="relative mx-auto h-[380px] w-full max-w-[420px]">
            <div className="absolute inset-0 rounded-full brand-gradient opacity-40 blur-3xl" />
            <div className="absolute inset-8 rounded-full brand-gradient opacity-20 blur-2xl" />
            <div
              className="animate-float absolute left-0 top-6 h-40 w-40 -rotate-6 border-2 bg-surface p-3 shadow-md"
              style={{ borderColor: '#F5871F' }}
            >
              <ProductMockup mockup="tshirt" color="#F5871F" />
            </div>
            <div
              className="animate-float absolute right-2 top-0 h-36 w-36 rotate-6 border-2 bg-surface p-3 shadow-md"
              style={{ borderColor: '#1EA7E0', animationDelay: '1.5s' }}
            >
              <ProductMockup mockup="mug" color="#1EA7E0" />
            </div>
            <div
              className="animate-float absolute bottom-0 left-16 h-44 w-44 rotate-3 border-2 bg-surface p-3 shadow-md"
              style={{ borderColor: '#5B2C86', animationDelay: '3s' }}
            >
              <ProductMockup mockup="phonecase" color="#5B2C86" />
            </div>
          </Reveal>
        </div>
      </section>

      {/* Reassurance strip */}
      <section className="border-y border-line bg-surface">
        <div className="mx-auto grid max-w-6xl gap-6 px-6 py-8 sm:grid-cols-2 lg:grid-cols-4">
          {REASSURANCES.map((r) => (
            <div key={r.label}>
              <p className="tag-label text-ink">{r.label}</p>
              <p className="mt-1 text-sm text-muted">{r.body}</p>
            </div>
          ))}
        </div>
      </section>

      {/* Choose your path — equal-weight split so this isn't just a funnel into personalizing */}
      <section className="mx-auto max-w-6xl px-6 py-16">
        <Reveal className="grid gap-5 md:grid-cols-2">
          {/* Personalise card */}
          <div className="group relative overflow-hidden border-2 border-ink bg-surface p-8">
            <div className="absolute -right-10 -top-10 h-40 w-40 rounded-full brand-gradient opacity-20 blur-2xl" />
            <p className="tag-label text-splash-pink">Design it yourself</p>
            <h2 className="mt-2 font-display text-3xl">Personalise</h2>
            <p className="mt-3 max-w-sm text-sm text-muted">
              Pick a template and make it yours with your own text and artwork, right in the
              browser.
            </p>
            <div className="mt-5 flex flex-wrap gap-2">
              {categories.map((c) => (
                <Link
                  key={c.value}
                  href={`/made-to-order?category=${c.value}`}
                  className="border border-line px-3 py-1.5 text-xs hover:border-clay hover:text-clay"
                >
                  {c.label}
                </Link>
              ))}
            </div>
            <Link href="/made-to-order" className="link-cta mt-6">
              Start designing <span aria-hidden>→</span>
            </Link>
          </div>

          {/* Ready-made card */}
          <div className="group relative overflow-hidden border-2 border-line bg-surface p-8">
            <div className="absolute -right-10 -top-10 h-40 w-40 rounded-full bg-splash-blue opacity-10 blur-2xl" />
            {readyMadeCount === 0 && (
              <span className="tag-label border border-line px-2 py-1 text-splash-blue">Coming soon</span>
            )}
            <h2 className="mt-3 font-display text-3xl">Ready-made</h2>
            <p className="mt-3 max-w-sm text-sm text-muted">
              {readyMadeCount === 0
                ? "Prefer to skip the design step? We're putting together a collection of ready-to-buy favorites — no personalizing required."
                : 'Prefer to skip the design step? Browse pieces that are ready to buy as-is — no personalizing required.'}
            </p>
            <Link href="/products" className="link-cta mt-6">
              Take a look <span aria-hidden>→</span>
            </Link>
          </div>
        </Reveal>
      </section>

      {/* Gallery preview — completed work, prominent placement near the top. Always
          shown (with a "coming soon" state when empty) so it never disappears
          entirely — a link this prominent shouldn't come and go with photo count. */}
      <section className="mx-auto max-w-6xl px-6 pb-16">
        <Reveal>
          <div className="mb-8 flex items-baseline justify-between">
            <div>
              <p className="tag-label text-splash-pink">Our work</p>
              <h2 className="mt-1 font-display text-3xl">From the gallery</h2>
            </div>
            <Link href="/gallery" className="link-cta">
              View gallery <span aria-hidden>→</span>
            </Link>
          </div>
          {galleryPhotos.length > 0 ? (
            <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
              {galleryPhotos.map((p) => (
                <Link
                  key={p.id}
                  href="/gallery"
                  className="group block aspect-square overflow-hidden border border-line bg-surface"
                >
                  <img
                    src={p.imageDataUrl}
                    alt={p.caption ?? 'Completed work'}
                    className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
                  />
                </Link>
              ))}
            </div>
          ) : (
            <Link
              href="/gallery"
              className="block border border-line bg-surface p-10 text-center transition-colors hover:border-clay"
            >
              <p className="font-display text-xl">Photos coming soon</p>
              <p className="mt-2 text-sm text-muted">
                We&apos;re putting together a gallery of finished work — check back soon.
              </p>
            </Link>
          )}
        </Reveal>
      </section>

      {/* Custom photo request — only shown to logged-in customers */}
      {customer && (
        <section className="mx-auto max-w-6xl px-6 pb-16">
          <Reveal className="flex flex-col items-start gap-4 border-2 border-splash-pink/40 bg-surface p-8 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <p className="tag-label text-splash-pink">Got your own photo?</p>
              <h2 className="mt-2 font-display text-2xl">Send it our way and we'll work our magic</h2>
              <p className="mt-2 max-w-lg text-sm text-muted">
                Upload a photo and tell us what you'd like it on — we'll turn it into a design for
                you to review.
              </p>
            </div>
            <Link
              href="/custom-request"
              className="shrink-0 bg-clay px-6 py-3 text-sm font-medium text-paper transition-colors hover:bg-clay-dark"
            >
              Send us your photo
            </Link>
          </Reveal>
        </section>
      )}

      {/* Featured products */}
      <section className="mx-auto max-w-6xl px-6 pb-20">
        <Reveal>
          <div className="mb-8 flex items-baseline justify-between">
            <h2 className="font-display text-3xl">Popular templates</h2>
            <Link href="/made-to-order" className="link-cta">
              View all <span aria-hidden>→</span>
            </Link>
          </div>
          <div className="grid gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-4">
            {featured.map((p) => (
              <ProductCard key={p.id} product={p} />
            ))}
          </div>
        </Reveal>
      </section>

      {/* Ready-made favourites */}
      {readyMadeCount > 0 && (
        <section className="mx-auto max-w-6xl px-6 pb-20">
          <Reveal>
            <div className="mb-8 flex items-baseline justify-between">
              <h2 className="font-display text-3xl">Ready-made favorites</h2>
              <Link href="/products" className="link-cta">
                View all <span aria-hidden>→</span>
              </Link>
            </div>
            <div className="grid gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-4">
              {readyMade.map((p) => (
                <ProductCard key={p.id} product={p} hrefBase="/products" />
              ))}
            </div>
          </Reveal>
        </section>
      )}

      {/* How it works */}
      <div className="h-1 w-full brand-gradient" />
      <section id="how-it-works" className="bg-surface">
        <Reveal className="mx-auto max-w-6xl px-6 py-20">
          <h2 className="font-display text-3xl">How it works</h2>
          <div className="mt-10 grid gap-10 md:grid-cols-3">
            {steps.map((s) => (
              <div key={s.n}>
                <p className="font-display text-4xl brand-gradient-text">{s.n}</p>
                <p className="mt-3 text-lg font-medium">{s.title}</p>
                <p className="mt-2 text-sm text-muted">{s.body}</p>
              </div>
            ))}
          </div>
        </Reveal>
      </section>

      {/* CTA banner */}
      <section className="brand-gradient">
        <Reveal className="mx-auto flex max-w-6xl flex-col items-center gap-5 px-6 py-16 text-center text-white">
          <h2 className="font-display text-3xl md:text-4xl">Ready to make it yours?</h2>
          <div className="flex flex-wrap items-center justify-center gap-3">
            <Link
              href="/made-to-order"
              className="bg-clay px-7 py-3 text-sm font-medium text-paper transition-colors hover:bg-white hover:text-clay-dark"
            >
              Browse templates
            </Link>
            <Link
              href="/products"
              className="border-2 border-white px-7 py-3 text-sm font-medium text-white transition-colors hover:bg-white hover:text-clay-dark"
            >
              See ready-made
            </Link>
          </div>
        </Reveal>
      </section>
    </div>
  );
}
