import Link from "next/link";
import Image from "next/image";
import {
  ArrowRight,
  Banknote,
  Package,
  ShoppingBag,
  TrendingUp,
  Users,
} from "lucide-react";
import { prisma } from "@/lib/prisma";
import { formatPrice } from "@/lib/money";
import { productTitle } from "@/lib/catalog";
import { AdminPageHeader } from "@/components/admin/page-header";
import { AdminStat } from "@/components/admin/stat-card";
import { OrderStatusBadge } from "@/components/admin/status-badge";
import { Button } from "@/components/ui/button";

function startOfWeek(date: Date) {
  const result = new Date(date);
  result.setHours(0, 0, 0, 0);
  const offset = (result.getDay() + 6) % 7;
  result.setDate(result.getDate() - offset);
  return result;
}

const dateShort = new Intl.DateTimeFormat("fr-FR", { day: "numeric", month: "short" });
const dateLong = new Intl.DateTimeFormat("fr-FR", { day: "2-digit", month: "short", year: "numeric" });

export default async function AdminDashboardPage() {
  const now = new Date();
  const eightWeeksAgo = startOfWeek(now);
  eightWeeksAgo.setDate(eightWeeksAgo.getDate() - 7 * 7);
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const previousMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);

  const [recentOrders, activeOrders, productCount, customerCount, allProducts, topGroups, messages] =
    await Promise.all([
      prisma.order.findMany({
        orderBy: { createdAt: "desc" },
        take: 6,
        include: { _count: { select: { items: true } } },
      }),
      prisma.order.findMany({
        where: { status: { in: ["PENDING", "CONFIRMED", "PROCESSING"] } },
        select: { id: true, total: true, status: true },
      }),
      prisma.product.count(),
      prisma.user.count({ where: { role: "CUSTOMER" } }),
      prisma.product.findMany({
        select: {
          id: true,
          slug: true,
          stock: true,
          lowStockThreshold: true,
          translations: true,
          images: { orderBy: { position: "asc" }, take: 1 },
        },
      }),
      prisma.orderItem.groupBy({
        by: ["productId"],
        _sum: { quantity: true, total: true },
        orderBy: { _sum: { quantity: "desc" } },
        take: 5,
      }),
      prisma.contactMessage.count({ where: { isRead: false } }),
    ]);

  const recentRevenueOrders = await prisma.order.findMany({
    where: { status: { not: "CANCELLED" } },
    select: { total: true, createdAt: true },
  });

  const revenue = recentRevenueOrders.reduce((sum, order) => sum + order.total, 0);
  const averageOrder = recentRevenueOrders.length ? Math.round(revenue / recentRevenueOrders.length) : 0;
  const monthOrders = recentRevenueOrders.filter((order) => order.createdAt >= monthStart);
  const previousMonthOrders = recentRevenueOrders.filter(
    (order) => order.createdAt >= previousMonthStart && order.createdAt < monthStart,
  );
  const monthRevenue = monthOrders.reduce((sum, order) => sum + order.total, 0);
  const previousMonthRevenue = previousMonthOrders.reduce((sum, order) => sum + order.total, 0);
  const monthTrend =
    previousMonthRevenue > 0
      ? Math.round(((monthRevenue - previousMonthRevenue) / previousMonthRevenue) * 100)
      : null;

  const weeks = Array.from({ length: 8 }, (_, index) => {
    const start = new Date(eightWeeksAgo);
    start.setDate(start.getDate() + index * 7);
    const end = new Date(start);
    end.setDate(end.getDate() + 7);
    const orders = recentRevenueOrders.filter((order) => order.createdAt >= start && order.createdAt < end);
    return {
      start,
      total: orders.reduce((sum, order) => sum + order.total, 0),
      count: orders.length,
    };
  });
  const maxWeek = Math.max(...weeks.map((week) => week.total), 1);

  const lowStock = allProducts
    .filter((product) => product.stock <= product.lowStockThreshold)
    .sort((a, b) => a.stock - b.stock);

  const topIds = topGroups
    .map((group) => group.productId)
    .filter((id): id is string => Boolean(id));
  const topProducts = await prisma.product.findMany({
    where: { id: { in: topIds } },
    include: { translations: true, images: { orderBy: { position: "asc" }, take: 1 } },
  });
  const topSorted = topGroups
    .map((group) => {
      const product = topProducts.find((item) => item.id === group.productId);
      return product ? { product, quantity: group._sum.quantity ?? 0, total: group._sum.total ?? 0 } : null;
    })
    .filter(Boolean) as { product: (typeof topProducts)[number]; quantity: number; total: number }[];

  const pendingTotal = activeOrders
    .filter((order) => order.status === "PENDING")
    .reduce((sum, order) => sum + order.total, 0);

  return (
    <div className="space-y-6">
      <AdminPageHeader
        eyebrow="Tableau de bord"
        title="Vue d'ensemble"
        description="L'activité de la maison en un regard : ventes, commandes à traiter, stock et clientèle."
        actions={
          <Button asChild size="sm">
            <Link href="/admin/products/new">
              <Package className="h-4 w-4" />
              Nouveau produit
            </Link>
          </Button>
        }
      />

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <AdminStat
          label="Chiffre d'affaires"
          value={formatPrice(revenue)}
          hint={
            monthRevenue > 0
              ? `${formatPrice(monthRevenue)} ce mois-ci${monthTrend === null ? "" : ` · ${monthTrend >= 0 ? "+" : ""}${monthTrend} % vs mois précédent`}`
              : "Aucune vente ce mois-ci"
          }
          icon={<Banknote className="h-4 w-4" strokeWidth={1.4} />}
          tone="gold"
        />
        <AdminStat
          label="Commandes"
          value={String(recentRevenueOrders.length)}
          hint={`${activeOrders.length} en cours de traitement`}
          icon={<ShoppingBag className="h-4 w-4" strokeWidth={1.4} />}
          href="/admin/orders"
        />
        <AdminStat
          label="Panier moyen"
          value={formatPrice(averageOrder)}
          hint={`${monthOrders.length} commande(s) ce mois-ci`}
          icon={<TrendingUp className="h-4 w-4" strokeWidth={1.4} />}
          tone="olive"
        />
        <AdminStat
          label="Clientèle"
          value={String(customerCount)}
          hint={`${productCount} produits au catalogue`}
          icon={<Users className="h-4 w-4" strokeWidth={1.4} />}
          href="/admin/customers"
        />
      </div>

      <div className="grid gap-4 xl:grid-cols-[1.55fr_1fr]">
        <section className="min-w-0 border border-line bg-cream p-5">
          <div className="flex items-start justify-between">
            <div>
              <h2 className="font-serif text-xl font-light">Ventes des 8 dernières semaines</h2>
              <p className="mt-1 text-[13px] text-pebble">Total encaissé, hors commandes annulées</p>
            </div>
            <p className="font-serif text-2xl font-light">{formatPrice(weeks.reduce((sum, week) => sum + week.total, 0))}</p>
          </div>

          <div className="mt-8 flex h-52 items-end gap-2 md:gap-3">
            {weeks.map((week) => (
              <div key={week.start.toISOString()} className="flex h-full flex-1 flex-col items-center justify-end gap-2">
                <p className="text-[12px] tabular-nums text-pebble">
                  {week.total > 0 ? Math.round(week.total / 100).toLocaleString("fr-FR") : "—"}
                </p>
                <div
                  className="group relative w-full max-w-[46px] bg-cream"
                  style={{ height: `${Math.max(4, (week.total / maxWeek) * 100)}%` }}
                  title={`Semaine du ${dateShort.format(week.start)} — ${formatPrice(week.total)} · ${week.count} commande(s)`}
                >
                  <div className="absolute inset-0 bg-gold/60 transition-colors group-hover:bg-gold" />
                </div>
                <p className="whitespace-nowrap text-[12px] uppercase tracking-[0.08em] text-pebble">
                  {dateShort.format(week.start)}
                </p>
              </div>
            ))}
          </div>
        </section>

        <section className="flex min-w-0 flex-col border border-line bg-cream p-5">
          <h2 className="font-serif text-xl font-light">À traiter</h2>
          <div className="mt-5 space-y-3">
            <Link
              href="/admin/orders?status=PENDING"
              className="flex items-center justify-between border border-line px-4 py-3 transition-colors hover:border-charcoal/30"
            >
              <div>
                <p className="text-[14px] text-charcoal">Commandes en attente</p>
                <p className="mt-0.5 text-[12px] text-pebble">{formatPrice(pendingTotal)} à confirmer</p>
              </div>
              <span className="font-serif text-2xl text-charcoal">
                {activeOrders.filter((order) => order.status === "PENDING").length}
              </span>
            </Link>
            <Link
              href="/admin/inventory"
              className="flex items-center justify-between border border-line px-4 py-3 transition-colors hover:border-charcoal/30"
            >
              <div>
                <p className="text-[14px] text-charcoal">Pièces en stock faible</p>
                <p className="mt-0.5 text-[12px] text-pebble">Seuil d'alerte atteint</p>
              </div>
              <span className="font-serif text-2xl text-terracotta">{lowStock.length}</span>
            </Link>
            <Link
              href="/admin/content"
              className="flex items-center justify-between border border-line px-4 py-3 transition-colors hover:border-charcoal/30"
            >
              <div>
                <p className="text-[14px] text-charcoal">Messages non lus</p>
                <p className="mt-0.5 text-[12px] text-pebble">Formulaire de contact</p>
              </div>
              <span className="font-serif text-2xl text-charcoal">{messages}</span>
            </Link>
          </div>

          <div className="mt-auto border-t border-line pt-4">
            <Link
              href="/admin/orders"
              className="inline-flex items-center gap-2 text-[12px] uppercase tracking-[0.16em] text-pebble hover:text-charcoal"
            >
              Toutes les commandes
              <ArrowRight className="h-3 w-3" />
            </Link>
          </div>
        </section>
      </div>

      <div className="grid gap-4 xl:grid-cols-[1.55fr_1fr]">
        <section className="min-w-0 border border-line bg-cream">
          <div className="flex items-center justify-between border-b border-line px-5 py-4">
            <h2 className="font-serif text-xl font-light">Commandes récentes</h2>
            <Link href="/admin/orders" className="text-[12px] uppercase tracking-[0.14em] text-pebble hover:text-charcoal">
              Tout voir
            </Link>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-left text-[14px]">
              <thead>
                <tr className="border-b border-line text-[12px] uppercase tracking-[0.14em] text-pebble">
                  <th className="px-5 py-3 font-medium">Référence</th>
                  <th className="px-3 py-3 font-medium">Client</th>
                  <th className="px-3 py-3 font-medium">Date</th>
                  <th className="px-3 py-3 font-medium">Statut</th>
                  <th className="px-5 py-3 text-right font-medium">Total</th>
                </tr>
              </thead>
              <tbody>
                {recentOrders.map((order) => (
                  <tr key={order.id} className="border-b border-line/70 last:border-0 hover:bg-cream/40">
                    <td className="px-5 py-3.5">
                      <Link href={`/admin/orders/${order.id}`} className="font-medium tracking-wide text-charcoal hover:underline">
                        {order.reference}
                      </Link>
                      <p className="mt-0.5 text-[12px] text-pebble">{order._count.items} article(s)</p>
                    </td>
                    <td className="px-3 py-3.5">
                      <p className="text-charcoal/80">{order.customerName}</p>
                      <p className="mt-0.5 text-[12px] text-pebble">{order.city}</p>
                    </td>
                    <td className="px-3 py-3.5 text-pebble">{dateLong.format(order.createdAt)}</td>
                    <td className="px-3 py-3.5"><OrderStatusBadge status={order.status} /></td>
                    <td className="px-5 py-3.5 text-right tabular-nums text-charcoal">{formatPrice(order.total)}</td>
                  </tr>
                ))}
                {recentOrders.length === 0 && (
                  <tr>
                    <td colSpan={5} className="px-5 py-10 text-center text-[14px] text-pebble">
                      Aucune commande pour le moment.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </section>

        <section className="min-w-0 border border-line bg-cream">
          <div className="flex items-center justify-between border-b border-line px-5 py-4">
            <h2 className="font-serif text-xl font-light">Pièces les plus vendues</h2>
          </div>
          <div className="divide-y divide-border">
            {topSorted.map(({ product, quantity, total }, index) => {
              const image = product.images[0];
              return (
                <Link
                  key={product.id}
                  href={`/admin/products/${product.id}`}
                  className="flex items-center gap-3 px-5 py-3 transition-colors hover:bg-cream/40"
                >
                  <span className="w-4 font-serif text-sm text-pebble">{String(index + 1).padStart(2, "0")}</span>
                  <div className="relative h-11 w-11 shrink-0 overflow-hidden bg-cream">
                    {image && <Image src={image.url} alt={image.alt} fill sizes="44px" className="object-cover" />}
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-[14px] text-charcoal">{productTitle(product, "fr")}</p>
                    <p className="mt-0.5 text-[12px] text-pebble">{quantity} vendue(s)</p>
                  </div>
                  <p className="text-[13px] tabular-nums text-pebble">{formatPrice(total)}</p>
                </Link>
              );
            })}
            {topSorted.length === 0 && (
              <p className="px-5 py-10 text-center text-[14px] text-pebble">Pas encore de ventes.</p>
            )}
          </div>
        </section>
      </div>

      <section className="min-w-0 border border-line bg-cream">
        <div className="flex items-center justify-between border-b border-line px-5 py-4">
          <div className="flex items-center gap-2">
            <h2 className="font-serif text-xl font-light">Stock à surveiller</h2>
            {lowStock.length > 0 && (
              <span className="bg-terracotta/10 px-2 py-0.5 text-[12px] uppercase tracking-[0.1em] text-terracotta">
                {lowStock.length}
              </span>
            )}
          </div>
          <Link href="/admin/inventory" className="text-[12px] uppercase tracking-[0.14em] text-pebble hover:text-charcoal">
            Gérer l'inventaire
          </Link>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left text-[14px]">
            <thead>
              <tr className="border-b border-line text-[12px] uppercase tracking-[0.14em] text-pebble">
                <th className="px-5 py-3 font-medium">Pièce</th>
                <th className="px-3 py-3 font-medium">Stock</th>
                <th className="px-3 py-3 font-medium">Seuil</th>
                <th className="px-5 py-3 text-right font-medium">Action</th>
              </tr>
            </thead>
            <tbody>
              {lowStock.slice(0, 6).map((product) => (
                <tr key={product.id} className="border-b border-line/70 last:border-0">
                  <td className="px-5 py-3">
                    <div className="flex items-center gap-3">
                      <div className="relative h-9 w-9 overflow-hidden bg-cream">
                        {product.images[0] && (
                          <Image src={product.images[0].url} alt={product.images[0].alt} fill sizes="36px" className="object-cover" />
                        )}
                      </div>
                      <span className="text-charcoal/80">{productTitle(product, "fr")}</span>
                    </div>
                  </td>
                  <td className="px-3 py-3">
                    <span className={product.stock === 0 ? "text-terracotta" : "text-amber-700"}>
                      {product.stock === 0 ? "Épuisé" : `${product.stock} unité(s)`}
                    </span>
                  </td>
                  <td className="px-3 py-3 text-pebble">{product.lowStockThreshold}</td>
                  <td className="px-5 py-3 text-right">
                    <Link href={`/admin/products/${product.id}`} className="text-[12px] uppercase tracking-[0.12em] text-pebble hover:text-charcoal">
                      Réapprovisionner
                    </Link>
                  </td>
                </tr>
              ))}
              {lowStock.length === 0 && (
                <tr>
                  <td colSpan={4} className="px-5 py-10 text-center text-[14px] text-pebble">
                    Tous les stocks sont au-dessus du seuil.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}