"use client";

import { useMemo } from "react";
import { ShoppingCart, TrendingUp, Package, Truck, Clock, CheckCircle2 } from "lucide-react";

type OrderItem = {
  id: string;
  quantity: number;
  price: number;
  product: { id: string; name: string; type?: string };
  order: {
    status: string;
    createdAt: Date | string;
    shippingAddress?: string | null;
    shippingComuna?: string | null;
    shippingRegion?: string | null;
    user?: { name: string | null } | null;
    [key: string]: unknown;
  };
};

type Props = {
  items: OrderItem[];
  catalog: "TICKET" | "PHYSICAL";
};

const STATUS_LABEL: Record<string, { label: string; color: string }> = {
  PENDING:   { label: "Pendiente",  color: "text-yellow-400" },
  PAID:      { label: "Pagado",     color: "text-green-400" },
  SHIPPED:   { label: "Despachado", color: "text-blue-400" },
  DELIVERED: { label: "Entregado",  color: "text-emerald-400" },
  CANCELLED: { label: "Cancelado",  color: "text-red-400" },
};

export default function AdminProductStats({ items, catalog }: Props) {
  const stats = useMemo(() => {
    const paid    = items.filter((i) => ["PAID","SHIPPED","DELIVERED"].includes(i.order.status));
    const pending = items.filter((i) => i.order.status === "PENDING");
    const shipped = items.filter((i) => ["SHIPPED","DELIVERED"].includes(i.order.status));
    const waiting = items.filter((i) => i.order.status === "PAID" && catalog === "PHYSICAL");

    const totalRevenue = paid.reduce((s, i) => s + i.price * i.quantity, 0);
    const totalUnits   = paid.reduce((s, i) => s + i.quantity, 0);
    const pendingUnits = pending.reduce((s, i) => s + i.quantity, 0);

    // Ventas por producto
    const byProduct: Record<string, { name: string; units: number; revenue: number }> = {};
    for (const item of paid) {
      const key = item.product.id;
      if (!byProduct[key]) byProduct[key] = { name: item.product.name, units: 0, revenue: 0 };
      byProduct[key].units   += item.quantity;
      byProduct[key].revenue += item.price * item.quantity;
    }

    return { totalRevenue, totalUnits, pendingUnits, shippedCount: shipped.length, waitingShip: waiting.length, byProduct };
  }, [items, catalog]);

  // Últimas 5 líneas de pedido
  const recent = useMemo(
    () => [...items].sort((a, b) => new Date(b.order.createdAt).getTime() - new Date(a.order.createdAt).getTime()).slice(0, 8),
    [items]
  );

  if (items.length === 0) return null;

  return (
    <div className="space-y-4">
      {/* KPIs */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <StatCard
          icon={<TrendingUp className="w-5 h-5 text-green-400" />}
          label="Ingresos totales"
          value={`$${stats.totalRevenue.toLocaleString("es-CL")}`}
          sub="ventas confirmadas"
        />
        <StatCard
          icon={<ShoppingCart className="w-5 h-5 text-[#0ea5c6]" />}
          label={catalog === "TICKET" ? "Tickets vendidos" : "Unidades vendidas"}
          value={stats.totalUnits.toString()}
          sub="unidades pagadas"
        />
        {catalog === "PHYSICAL" && (
          <>
            <StatCard
              icon={<Clock className="w-5 h-5 text-yellow-400" />}
              label="Esperando despacho"
              value={stats.waitingShip.toString()}
              sub="pedidos pagados"
              highlight={stats.waitingShip > 0}
            />
            <StatCard
              icon={<Truck className="w-5 h-5 text-blue-400" />}
              label="Despachados"
              value={stats.shippedCount.toString()}
              sub="enviados / entregados"
            />
          </>
        )}
        {catalog === "TICKET" && (
          <>
            <StatCard
              icon={<Clock className="w-5 h-5 text-yellow-400" />}
              label="Pago pendiente"
              value={stats.pendingUnits.toString()}
              sub="tickets sin confirmar"
              highlight={stats.pendingUnits > 0}
            />
            <StatCard
              icon={<CheckCircle2 className="w-5 h-5 text-emerald-400" />}
              label="Productos activos"
              value={Object.keys(stats.byProduct).length.toString()}
              sub="packs con ventas"
            />
          </>
        )}
      </div>

      {/* Ventas por producto */}
      {Object.keys(stats.byProduct).length > 0 && (
        <div className="rounded-xl border border-white/10 overflow-hidden">
          <div className="px-4 py-3 border-b border-white/10 flex items-center gap-2">
            <Package className="w-4 h-4 text-[#0ea5c6]" />
            <span className="text-sm font-bold text-white">Ventas por producto</span>
          </div>
          <div className="divide-y divide-white/5">
            {Object.values(stats.byProduct)
              .sort((a, b) => b.revenue - a.revenue)
              .map((p) => (
                <div key={p.name} className="flex items-center justify-between px-4 py-3 text-sm">
                  <span className="text-gray-300 truncate max-w-[60%]">{p.name}</span>
                  <div className="flex gap-4 shrink-0">
                    <span className="text-gray-400">{p.units} uds.</span>
                    <span className="font-bold text-green-400">${p.revenue.toLocaleString("es-CL")}</span>
                  </div>
                </div>
              ))}
          </div>
        </div>
      )}

      {/* Últimos pedidos */}
      <div className="rounded-xl border border-white/10 overflow-hidden">
        <div className="px-4 py-3 border-b border-white/10">
          <span className="text-sm font-bold text-white">Últimas ventas</span>
        </div>
        <div className="divide-y divide-white/5">
          {recent.map((item) => {
            const s = STATUS_LABEL[item.order.status] ?? { label: item.order.status, color: "text-gray-400" };
            return (
              <div key={item.id} className="flex flex-col sm:flex-row sm:items-center justify-between px-4 py-3 text-xs gap-1">
                <div className="flex flex-col">
                  <span className="text-gray-200 font-medium">{item.product.name}</span>
                  <span className="text-gray-500">
                    {item.order.user?.name || "—"} ·{" "}
                    {new Date(item.order.createdAt).toLocaleDateString("es-CL")}
                  </span>
                  {catalog === "PHYSICAL" && item.order.shippingComuna && (
                    <span className="text-gray-500">
                      📍 {item.order.shippingComuna}, {item.order.shippingRegion}
                    </span>
                  )}
                </div>
                <div className="flex items-center gap-3 shrink-0">
                  <span className="text-gray-400">{item.quantity} uds.</span>
                  <span className="text-green-400 font-bold">${(item.price * item.quantity).toLocaleString("es-CL")}</span>
                  <span className={`font-bold uppercase tracking-wide ${s.color}`}>{s.label}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function StatCard({
  icon,
  label,
  value,
  sub,
  highlight = false,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  sub: string;
  highlight?: boolean;
}) {
  return (
    <div
      className={`rounded-xl border p-4 flex flex-col gap-1 ${
        highlight
          ? "border-yellow-500/40 bg-yellow-500/5"
          : "border-white/10 bg-white/5"
      }`}
    >
      <div className="flex items-center gap-2">
        {icon}
        <span className="text-xs text-gray-400 font-medium">{label}</span>
      </div>
      <span className="text-2xl font-black text-white">{value}</span>
      <span className="text-[10px] text-gray-500 uppercase tracking-wide">{sub}</span>
    </div>
  );
}
