import Link from "next/link";
import Image from "next/image";
import { ExternalLink, Pencil, Plus, Search } from "lucide-react";
import type { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { formatPrice } from "@/lib/money";
import { categoryTitle, productTitle } from "@/lib/catalog";
import { parsePage } from "@/lib/utils";
import { AdminPageHeader } from "@/components/admin/page-header";
import { Pagination } from "@/components/store/pagination";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { toggleProductPublishedAction } from "@/app/actions/admin-products";

const PAGE_SIZE = 20;

const selectClass =
  "h-9 w-full border border-line bg-cream px-2.5 text-[14px] text-charcoal focus:border-charcoal focus:outline-none";

export default async function AdminProductsPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const q = typeof params.q === "string" ? params.q.trim() : "";
  const categoryId = typeof params.category === "string" ? params.category : "";
  const status = typeof params.status === "string" ? params.status : "";
  const stock = typeof params.stock === "string" ? params.stock : "";
  const page = parsePage(params.page);

  const where: Prisma.ProductWhereInput = {
    ...(q
      ? {
          OR: [
            { sku: { contains: q } },
            { slug: { contains: q } },
            { translations: { some: { name: { contains: q } } } },
          ],
        }
      : {}),
    ...(categoryId ? { categoryId } : {}),
    ...(status === "published" ? { isPublished: true } : {}),
    ...(status === "draft" ? { isPublished: false } : {}),
    ...(stock === "out" ? { stock: 0 } : {}),
    ...(stock === "low" ? { stock: { gt: 0, lte: 8 } } : {}),
  };

  const [products, total, categories, counts] = await Promise.all([
    prisma.product.findMany({
      where,
      include: {
        translations: true,
        category: { include: { translations: true } },
        images: { orderBy: { position: "asc" }, take: 1 },
        _count: { select: { variants: true, orderItems: true } },
      },
      orderBy: { updatedAt: "desc" },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
    }),
    prisma.product.count({ where }),
    prisma.category.findMany({ include: { translations: true }, orderBy: { position: "asc" } }),
    prisma.product.groupBy({ by: ["isPublished"], _count: { _all: true } }),
  ]);

  const totalAll = counts.reduce((sum, entry) => sum + entry._count._all, 0);
  const published = counts.find((entry) => entry.isPublished)?._count._all ?? 0;
  const drafts = totalAll - published;
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  return (
    <div className="space-y-5">
      <AdminPageHeader
        eyebrow="Catalogue"
        title="Produits"
        description={`${totalAll} pièce(s) au catalogue · ${published} publiée(s) · ${drafts} brouillon(s)${total !== totalAll ? ` · ${total} dans cette vue` : ""}`}
        actions={
          <Button asChild size="sm">
            <Link href="/admin/products/new">
              <Plus className="h-4 w-4" />
              Nouveau produit
            </Link>
          </Button>
        }
      />

      {typeof params.deleted === "string" && (
        <p className="border border-olive/25 bg-olive/5 px-4 py-3 text-[14px] text-olive">
          Le produit a été supprimé.
        </p>
      )}

      <form className="grid gap-2 border border-line bg-cream p-3 md:grid-cols-[1fr_180px_150px_150px_auto]">
        <div className="relative">
          <Search className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-pebble" />
          <Input
            name="q"
            defaultValue={q}
            placeholder="Rechercher un nom, un slug ou un SKU…"
            className="h-9 rounded-none border-line bg-transparent pl-8 text-[14px]"
          />
        </div>
        <select name="category" defaultValue={categoryId} className={selectClass}>
          <option value="">Toutes catégories</option>
          {categories.map((category) => (
            <option key={category.id} value={category.id}>
              {categoryTitle(category, "fr")}
            </option>
          ))}
        </select>
        <select name="status" defaultValue={status} className={selectClass}>
          <option value="">Tous statuts</option>
          <option value="published">Publiés</option>
          <option value="draft">Brouillons</option>
        </select>
        <select name="stock" defaultValue={stock} className={selectClass}>
          <option value="">Tout le stock</option>
          <option value="low">Stock faible</option>
          <option value="out">Épuisés</option>
        </select>
        <div className="flex gap-2">
          <button
            type="submit"
            className="h-9 bg-charcoal px-4 text-[12px] uppercase tracking-[0.14em] text-ivory hover:opacity-90"
          >
            Filtrer
          </button>
          <Link
            href="/admin/products"
            className="flex h-9 items-center border border-line px-3 text-[12px] uppercase tracking-[0.12em] text-pebble hover:border-charcoal/40"
          >
            Effacer
          </Link>
        </div>
      </form>

      <div className="overflow-x-auto border border-line bg-cream">
        <table className="w-full min-w-[860px] text-left text-[14px]">
          <thead>
            <tr className="border-b border-line text-[12px] uppercase tracking-[0.14em] text-pebble">
              <th className="px-4 py-3 font-medium">Produit</th>
              <th className="px-3 py-3 font-medium">Catégorie</th>
              <th className="px-3 py-3 font-medium">Prix</th>
              <th className="px-3 py-3 font-medium">Stock</th>
              <th className="px-3 py-3 font-medium">Statut</th>
              <th className="px-3 py-3 font-medium">Variantes</th>
              <th className="px-4 py-3 text-right font-medium">Actions</th>
            </tr>
          </thead>
          <tbody>
            {products.map((product) => {
              const image = product.images[0];
              const low = product.stock <= product.lowStockThreshold;
              return (
                <tr key={product.id} className="border-b border-line/70 last:border-0 hover:bg-cream/30">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      <div className="relative h-12 w-12 shrink-0 overflow-hidden bg-cream">
                        {image ? (
                          <Image src={image.url} alt={image.alt} fill sizes="48px" className="object-cover" />
                        ) : (
                          <div className="flex h-full items-center justify-center text-[12px] text-pebble">—</div>
                        )}
                      </div>
                      <div className="min-w-0">
                        <Link href={`/admin/products/${product.id}`} className="block truncate font-medium text-charcoal hover:underline">
                          {productTitle(product, "fr")}
                        </Link>
                        <p className="mt-0.5 text-[12px] text-pebble">{product.sku} · {product.slug}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-3 text-pebble">{categoryTitle(product.category, "fr")}</td>
                  <td className="px-3 py-3 tabular-nums">
                    <p className="text-charcoal">{formatPrice(product.price)}</p>
                    {product.compareAtPrice && (
                      <p className="text-[12px] text-pebble line-through">{formatPrice(product.compareAtPrice)}</p>
                    )}
                  </td>
                  <td className="px-3 py-3">
                    <span className={product.stock === 0 ? "text-terracotta" : low ? "text-amber-700" : "text-walnut"}>
                      {product.stock === 0 ? "Épuisé" : `${product.stock} u.`}
                    </span>
                  </td>
                  <td className="px-3 py-3">
                    <div className="flex flex-col items-start gap-1">
                      <span
                        className={
                          product.isPublished
                            ? "border border-olive/25 bg-olive/5 px-1.5 py-0.5 text-[12px] uppercase tracking-[0.1em] text-olive"
                            : "border border-charcoal/15 bg-charcoal/5 px-1.5 py-0.5 text-[12px] uppercase tracking-[0.1em] text-pebble"
                        }
                      >
                        {product.isPublished ? "Publié" : "Brouillon"}
                      </span>
                      {product.isFeatured && (
                        <span className="text-[12px] uppercase tracking-[0.1em] text-gold-ink">Sélection</span>
                      )}
                    </div>
                  </td>
                  <td className="px-3 py-3 text-pebble">{product._count.variants}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center justify-end gap-1">
                      <form action={toggleProductPublishedAction}>
                        <input type="hidden" name="id" value={product.id} />
                        <button
                          type="submit"
                          className="px-2 py-1 text-[12px] uppercase tracking-[0.1em] text-pebble hover:text-charcoal"
                        >
                          {product.isPublished ? "Dépublier" : "Publier"}
                        </button>
                      </form>
                      <Link
                        href={`/admin/products/${product.id}`}
                        className="flex h-7 w-7 items-center justify-center border border-line text-pebble hover:border-charcoal/40 hover:text-charcoal"
                        aria-label="Modifier"
                      >
                        <Pencil className="h-3 w-3" />
                      </Link>
                      <Link
                        href={`/fr/product/${product.slug}`}
                        target="_blank"
                        className="flex h-7 w-7 items-center justify-center border border-line text-pebble hover:border-charcoal/40 hover:text-charcoal"
                        aria-label="Voir en boutique"
                      >
                        <ExternalLink className="h-3 w-3" />
                      </Link>
                    </div>
                  </td>
                </tr>
              );
            })}
            {products.length === 0 && (
              <tr>
                <td colSpan={7} className="px-4 py-16 text-center">
                  <p className="text-[14px] text-pebble">Aucun produit ne correspond à ces filtres.</p>
                  <Link href="/admin/products/new" className="mt-2 inline-block text-[13px] text-charcoal underline underline-offset-4">
                    Créer un produit
                  </Link>
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <Pagination
        page={page}
        totalPages={totalPages}
        basePath="/admin/products"
        params={{
          q: q || undefined,
          category: categoryId || undefined,
          status: status || undefined,
          stock: stock || undefined,
        }}
        labels={{ previous: "Page précédente", next: "Page suivante" }}
      />
    </div>
  );
}