import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { ArrowLeft, ExternalLink, History } from "lucide-react";
import { prisma } from "@/lib/prisma";
import { translationFor } from "@/lib/catalog";
import { formatPrice } from "@/lib/money";
import { AdminPageHeader } from "@/components/admin/page-header";
import { StockAdjustForm } from "@/components/admin/stock-adjust-form";
import { formatMovementType } from "@/lib/inventory";
import { Input } from "@/components/ui/input";

const typeClasses: Record<string, string> = {
  SALE: "border-terracotta/25 bg-terracotta/5 text-terracotta",
  RESTOCK: "border-olive/25 bg-olive/5 text-olive",
  ADJUSTMENT: "border-gold/30 bg-gold/5 text-gold-ink",
  CANCELLATION: "border-charcoal/15 bg-cream text-pebble",
};

export default async function AdminInventoryDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const product = await prisma.product.findUnique({
    where: { id },
    include: {
      translations: true,
      images: { take: 1, orderBy: { position: "asc" } },
      variants: { orderBy: { position: "asc" } },
      movements: {
        orderBy: { createdAt: "desc" },
        take: 50,
      },
    },
  });

  if (!product) notFound();

  const name = translationFor(product.translations, "fr")?.name ?? product.slug;
  const value = Math.max(0, product.stock) * (product.costPrice ?? 0);

  return (
    <div className="space-y-5">
      <Link href="/admin/inventory" className="inline-flex items-center gap-2 text-[12px] uppercase tracking-[0.14em] text-pebble hover:text-charcoal">
        <ArrowLeft className="h-3.5 w-3.5" />
        Inventaire
      </Link>

      <AdminPageHeader
        eyebrow="Mouvements de stock"
        title={name}
        description={`${product.sku} · ${product.stock} unité(s) · valeur ${formatPrice(value)}`}
        actions={
          <Link
            href={`/admin/products/${product.id}`}
            className="inline-flex h-9 items-center gap-2 border border-line px-3 text-[12px] uppercase tracking-[0.12em] text-pebble hover:border-charcoal/40"
          >
            <ExternalLink className="h-3.5 w-3.5" />
            Fiche produit
          </Link>
        }
      />

      <div className="grid gap-4 xl:grid-cols-[1fr_340px]">
        <div className="space-y-4">
          <section className="border border-line bg-cream">
            <div className="flex items-center gap-4 border-b border-line px-5 py-4">
              <div className="relative h-14 w-12 shrink-0 overflow-hidden bg-cream">
                {product.images[0] && (
                  <Image src={product.images[0].url} alt={name} fill sizes="48px" className="object-cover" />
                )}
              </div>
              <div className="flex-1">
                <p className="text-[14px] text-walnut">{name}</p>
                <p className="mt-0.5 font-mono text-[12px] text-pebble">{product.sku}</p>
              </div>
              <div className="text-right">
                <p className="text-[12px] uppercase tracking-[0.12em] text-pebble">Disponible</p>
                <p className={`font-serif text-3xl font-light ${product.stock <= 0 ? "text-terracotta" : product.stock <= product.lowStockThreshold ? "text-gold-ink" : "text-charcoal"}`}>
                  {product.stock}
                </p>
              </div>
            </div>
            <div className="px-5 py-4">
              <p className="text-[12px] uppercase tracking-[0.14em] text-pebble">Déclinaisons</p>
              <div className="mt-3 space-y-2">
                {product.variants.map((variant) => (
                  <div key={variant.id} className="flex items-center justify-between border-b border-line/70 pb-2 text-[14px] last:border-0">
                    <div>
                      <p className="text-charcoal/70">{variant.name}</p>
                      <p className="mt-0.5 font-mono text-[12px] text-pebble">{variant.sku}</p>
                    </div>
                    <div className="flex items-center gap-4">
                      <span className={variant.stock <= 0 ? "text-terracotta" : variant.stock <= 3 ? "text-gold-ink" : "text-charcoal/70"}>
                        {variant.stock} unité(s)
                      </span>
                      <span className="w-20 text-right text-[13px] tabular-nums text-pebble">
                        {variant.priceDelta === 0 ? "—" : `${variant.priceDelta > 0 ? "+" : ""}${formatPrice(variant.priceDelta)}`}
                      </span>
                    </div>
                  </div>
                ))}
                {product.variants.length === 0 && (
                  <p className="text-[13px] text-pebble">Aucune variante : stock unique.</p>
                )}
              </div>
            </div>
          </section>

          <section className="border border-line bg-cream">
            <div className="flex items-center justify-between border-b border-line px-5 py-4">
              <h2 className="flex items-center gap-2 font-serif text-xl font-light">
                <History className="h-4 w-4 text-pebble" />
                Historique des mouvements
              </h2>
              <span className="text-[12px] text-pebble">{product.movements.length} dernier(s)</span>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full min-w-[640px] text-left text-[13px]">
                <thead>
                  <tr className="border-b border-line text-[12px] uppercase tracking-[0.14em] text-pebble">
                    <th className="px-4 py-2.5 font-medium">Date</th>
                    <th className="px-3 py-2.5 font-medium">Type</th>
                    <th className="px-3 py-2.5 font-medium">Motif</th>
                    <th className="px-3 py-2.5 text-right font-medium">Variation</th>
                    <th className="px-3 py-2.5 text-right font-medium">Avant → après</th>
                  </tr>
                </thead>
                <tbody>
                  {product.movements.map((movement) => (
                    <tr key={movement.id} className="border-b border-line/70 last:border-0">
                      <td className="px-4 py-2.5 text-pebble">
                        {new Intl.DateTimeFormat("fr-FR", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" }).format(movement.createdAt)}
                      </td>
                      <td className="px-3 py-2.5">
                        <span className={`border px-1.5 py-0.5 text-[12px] uppercase tracking-[0.08em] ${typeClasses[movement.type] ?? "border-line text-pebble"}`}>
                          {formatMovementType(movement.type)}
                        </span>
                      </td>
                      <td className="max-w-[220px] px-3 py-2.5 text-pebble">
                        <p className="truncate" title={movement.reason ?? ""}>{movement.reason ?? "—"}</p>
                        {movement.orderId && <p className="mt-0.5 font-mono text-[12px] text-pebble">{movement.orderId}</p>}
                      </td>
                      <td className={`px-3 py-2.5 text-right tabular-nums ${movement.quantity > 0 ? "text-olive" : "text-terracotta"}`}>
                        {movement.quantity > 0 ? "+" : ""}{movement.quantity}
                      </td>
                      <td className="px-3 py-2.5 text-right tabular-nums text-pebble">
                        {movement.previousStock} → {movement.newStock}
                      </td>
                    </tr>
                  ))}
                  {product.movements.length === 0 && (
                    <tr>
                      <td colSpan={5} className="px-4 py-10 text-center text-[13px] text-pebble">
                        Aucun mouvement enregistré.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </section>
        </div>

        <aside className="space-y-4">
          <section className="border border-line bg-cream p-4">
            <h2 className="font-serif text-lg font-light">Ajuster le stock</h2>
            <p className="mt-1 text-[13px] leading-relaxed text-pebble">
              Chaque ajustement est tracé avec son motif et votre compte.
            </p>
            <div className="mt-4">
              <StockAdjustForm
                productId={product.id}
                productStock={product.stock}
                variants={product.variants.map((variant) => ({ id: variant.id, name: variant.name, stock: variant.stock }))}
              />
            </div>
          </section>

          <section className="border border-line bg-cream p-4">
            <h2 className="font-serif text-lg font-light">Seuil d'alerte</h2>
            <div className="mt-3 flex items-center gap-3">
              <Input
                type="number"
                defaultValue={product.lowStockThreshold}
                readOnly
                className="h-10 w-20 rounded-none tabular-nums"
              />
              <p className="text-[13px] leading-relaxed text-pebble">
                Une alerte apparaît sur le tableau de bord lorsque le stock descend à ce niveau.
              </p>
            </div>
            <Link href={`/admin/products/${product.id}`} className="mt-3 inline-block text-[12px] uppercase tracking-[0.12em] text-pebble underline-offset-4 hover:underline">
              Modifier le seuil
            </Link>
          </section>
        </aside>
      </div>
    </div>
  );
}