import Link from "next/link";
import Image from "next/image";
import { Search } from "lucide-react";
import type { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { categoryTitle, translationFor } from "@/lib/catalog";
import { formatPrice } from "@/lib/money";
import { AdminPageHeader } from "@/components/admin/page-header";
import { AdminStat } from "@/components/admin/stat-card";
import { Input } from "@/components/ui/input";
import { Package, AlertTriangle, PackageX, Coins } from "lucide-react";

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 AdminInventoryPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const q = typeof params.q === "string" ? params.q.trim() : "";
  const stockFilter = typeof params.stock === "string" ? params.stock : "";
  const categorySlug = typeof params.category === "string" ? params.category : "";

  const where: Prisma.ProductWhereInput = {
    ...(q
      ? {
          OR: [
            { sku: { contains: q } },
            { slug: { contains: q } },
            { translations: { some: { name: { contains: q } } } },
          ],
        }
      : {}),
    ...(categorySlug ? { category: { slug: categorySlug } } : {}),
    ...(stockFilter === "out" ? { stock: { lte: 0 } } : {}),
  };

  const [products, categories, allProducts] = await Promise.all([
    prisma.product.findMany({
      where,
      include: {
        images: { take: 1, orderBy: { position: "asc" } },
        translations: true,
        variants: { orderBy: { position: "asc" } },
        category: { include: { translations: true } },
      },
      orderBy: [{ stock: "asc" }, { updatedAt: "desc" }],
    }),
    prisma.category.findMany({ include: { translations: true }, orderBy: { position: "asc" } }),
    prisma.product.findMany({ select: { stock: true, costPrice: true, lowStockThreshold: true, isPublished: true } }),
  ]);

  const filtered = stockFilter === "low"
    ? products.filter((product) => product.stock > 0 && product.stock <= product.lowStockThreshold)
    : products;

  const totalUnits = allProducts.reduce((sum, product) => sum + Math.max(0, product.stock), 0);
  const stockValue = allProducts.reduce((sum, product) => sum + Math.max(0, product.stock) * (product.costPrice ?? 0), 0);
  const lowCount = allProducts.filter((product) => product.isPublished && product.stock > 0 && product.stock <= product.lowStockThreshold).length;
  const outCount = allProducts.filter((product) => product.stock <= 0).length;

  return (
    <div className="space-y-5">
      <AdminPageHeader
        eyebrow="Catalogue"
        title="Inventaire"
        description="Suivez les quantités disponibles, les seuils d'alerte et la valeur immobilisée."
      />

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <AdminStat label="Unités en stock" value={totalUnits.toLocaleString("fr-FR")} hint={`${allProducts.length} référence(s)`} icon={<Package className="h-4 w-4" strokeWidth={1.4} />} />
        <AdminStat label="Valeur du stock" value={formatPrice(stockValue)} hint="Au coût d'achat" tone="gold" icon={<Coins className="h-4 w-4" strokeWidth={1.4} />} />
        <AdminStat label="Stock faible" value={String(lowCount)} hint="Sous le seuil d'alerte" tone="olive" icon={<AlertTriangle className="h-4 w-4" strokeWidth={1.4} />} />
        <AdminStat label="Épuisés" value={String(outCount)} hint="À réapprovisionner" icon={<PackageX className="h-4 w-4" strokeWidth={1.4} />} />
      </div>

      <form className="grid gap-2 border border-line bg-cream p-3 md:grid-cols-[1fr_170px_200px_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="Nom ou SKU…"
            className="h-9 rounded-none border-line bg-transparent pl-8 text-[14px]"
          />
        </div>
        <select name="stock" defaultValue={stockFilter} className={selectClass}>
          <option value="">Tout le stock</option>
          <option value="low">Stock faible</option>
          <option value="out">Épuisés</option>
        </select>
        <select name="category" defaultValue={categorySlug} className={selectClass}>
          <option value="">Toutes catégories</option>
          {categories.map((category) => (
            <option key={category.id} value={category.slug}>{categoryTitle(category, "fr")}</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/inventory" 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-[900px] 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">SKU</th>
              <th className="px-3 py-3 font-medium">Catégorie</th>
              <th className="px-3 py-3 font-medium">Stock</th>
              <th className="px-3 py-3 font-medium">Variantes</th>
              <th className="px-3 py-3 font-medium">Valeur</th>
              <th className="px-4 py-3 text-right font-medium">Action</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((product) => {
              const low = product.stock > 0 && product.stock <= product.lowStockThreshold;
              const out = product.stock <= 0;
              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-10 w-9 shrink-0 overflow-hidden bg-cream">
                        {product.images[0] && (
                          <Image src={product.images[0].url} alt="" fill sizes="36px" className="object-cover" />
                        )}
                      </div>
                      <div>
                        <Link href={`/admin/inventory/${product.id}`} className="text-charcoal hover:underline">
                          {translationFor(product.translations, "fr")?.name ?? product.slug}
                        </Link>
                        {!product.isPublished && (
                          <span className="ml-2 border border-line px-1 py-0.5 text-[12px] uppercase tracking-[0.08em] text-pebble">Brouillon</span>
                        )}
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-3 font-mono text-[12px] text-pebble">{product.sku}</td>
                  <td className="px-3 py-3 text-pebble">{categoryTitle(product.category, "fr")}</td>
                  <td className="px-3 py-3">
                    <span className={out ? "text-terracotta" : low ? "text-gold-ink" : "text-charcoal"}>
                      {out ? "Épuisé" : `${product.stock} unité(s)`}
                    </span>
                    <p className="mt-0.5 text-[12px] text-pebble">Seuil : {product.lowStockThreshold}</p>
                  </td>
                  <td className="px-3 py-3 text-pebble">
                    {product.variants.length > 0 ? `${product.variants.length} option(s)` : "—"}
                  </td>
                  <td className="px-3 py-3 tabular-nums text-walnut">
                    {formatPrice(Math.max(0, product.stock) * (product.costPrice ?? 0))}
                  </td>
                  <td className="px-4 py-3 text-right">
                    <Link href={`/admin/inventory/${product.id}`} className="text-[12px] uppercase tracking-[0.12em] text-pebble hover:text-charcoal">
                      Ajuster
                    </Link>
                  </td>
                </tr>
              );
            })}
            {filtered.length === 0 && (
              <tr>
                <td colSpan={7} className="px-4 py-16 text-center text-[14px] text-pebble">
                  Aucun produit ne correspond à ces filtres.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
