"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { formatCop } from "@/data/products";
import { useAdmin } from "@/context/AdminContext";

type OtOrder = {
  id: string;
  display_id?: number;
  email?: string;
  total?: number;
  created_at?: string;
  status?: string;
  items?: {
    id: string;
    title?: string;
    quantity?: number;
    variant_title?: string;
    unit_price?: number;
  }[];
};

type Visits = {
  total: number;
  today: number;
  yesterday: number;
  week: { date: string; count: number }[];
  paths: { path: string; count: number }[];
};

function startOfDay(d: Date) {
  return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}

function inRange(iso: string | undefined, from: Date) {
  if (!iso) return false;
  return new Date(iso) >= from;
}

export default function NegocioVentasPage() {
  const { authenticated, loading: authLoading } = useAdmin();
  const [orders, setOrders] = useState<OtOrder[]>([]);
  const [visits, setVisits] = useState<Visits | null>(null);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    const [ordersRes, visitsRes] = await Promise.all([
      fetch("/api/ops/orders?status=all", { cache: "no-store" }),
      fetch("/api/ops/visits", { cache: "no-store" }),
    ]);
    if (ordersRes.ok) {
      const data = (await ordersRes.json()) as { orders?: OtOrder[] };
      setOrders(data.orders || []);
    }
    if (visitsRes.ok) setVisits((await visitsRes.json()) as Visits);
    setLoading(false);
  }, []);

  useEffect(() => {
    if (authenticated) load();
  }, [authenticated, load]);

  const metrics = useMemo(() => {
    const now = new Date();
    const dayStart = startOfDay(now);
    const weekStart = new Date(dayStart);
    weekStart.setDate(weekStart.getDate() - 6);
    const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);

    const paid = orders.filter((o) => o.status !== "cancelado");

    const sum = (list: OtOrder[]) =>
      list.reduce((acc, o) => acc + Number(o.total || 0), 0);

    const dayOrders = paid.filter((o) => inRange(o.created_at, dayStart));
    const weekOrders = paid.filter((o) => inRange(o.created_at, weekStart));
    const monthOrders = paid.filter((o) => inRange(o.created_at, monthStart));

    const productMap = new Map<
      string,
      { title: string; qty: number; revenue: number }
    >();
    for (const order of paid) {
      for (const item of order.items || []) {
        const key = item.title || "Prenda";
        const cur = productMap.get(key) || {
          title: key,
          qty: 0,
          revenue: 0,
        };
        const qty = Number(item.quantity || 1);
        cur.qty += qty;
        cur.revenue += qty * Number(item.unit_price || 0);
        productMap.set(key, cur);
      }
    }
    const topProducts = Array.from(productMap.values())
      .sort((a, b) => b.qty - a.qty || b.revenue - a.revenue)
      .slice(0, 8);

    return {
      day: { count: dayOrders.length, total: sum(dayOrders) },
      week: { count: weekOrders.length, total: sum(weekOrders) },
      month: { count: monthOrders.length, total: sum(monthOrders) },
      all: { count: paid.length, total: sum(paid) },
      canceled: orders.filter((o) => o.status === "cancelado").length,
      topProducts,
    };
  }, [orders]);

  if (authLoading || !authenticated) {
    return (
      <div className="text-sm text-ot-muted py-10">
        {authLoading ? "Cargando…" : "Inicia sesión en el panel."}
      </div>
    );
  }

  const cards = [
    {
      label: "Hoy",
      total: metrics.day.total,
      count: metrics.day.count,
    },
    {
      label: "7 días",
      total: metrics.week.total,
      count: metrics.week.count,
    },
    {
      label: "Mes",
      total: metrics.month.total,
      count: metrics.month.count,
    },
    {
      label: "Histórico",
      total: metrics.all.total,
      count: metrics.all.count,
    },
  ];

  return (
    <div className="space-y-8">
      <header>
        <p className="ot-eyebrow text-ot-gold">Métricas</p>
        <h1 className="font-serif text-4xl mt-1">Ventas</h1>
        <p className="mt-2 text-sm text-ot-muted max-w-xl">
          Resumen de pedidos pagados (sin cancelados) y visitas de la tienda.
        </p>
      </header>

      {loading ? (
        <p className="text-sm text-ot-muted">Actualizando…</p>
      ) : null}

      <div className="grid sm:grid-cols-2 xl:grid-cols-4 gap-3">
        {cards.map((c) => (
          <div
            key={c.label}
            className="bg-white border border-black/10 px-4 py-4"
          >
            <p className="text-[11px] tracking-[0.14em] uppercase text-ot-muted">
              {c.label}
            </p>
            <p className="font-serif text-3xl mt-2">{formatCop(c.total)}</p>
            <p className="text-xs text-ot-muted mt-1">
              {c.count} pedido{c.count === 1 ? "" : "s"}
            </p>
          </div>
        ))}
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        <section className="bg-white border border-black/10 p-5">
          <h2 className="font-serif text-2xl">Más vendidos</h2>
          {metrics.topProducts.length === 0 ? (
            <p className="mt-4 text-sm text-ot-muted">Aún no hay ventas.</p>
          ) : (
            <ul className="mt-4 divide-y divide-black/8">
              {metrics.topProducts.map((p) => (
                <li
                  key={p.title}
                  className="py-3 flex justify-between gap-3 text-sm"
                >
                  <span className="min-w-0">
                    <span className="block text-ot-ink truncate">{p.title}</span>
                    <span className="text-xs text-ot-muted">
                      {p.qty} uds
                    </span>
                  </span>
                  <span className="shrink-0">{formatCop(p.revenue)}</span>
                </li>
              ))}
            </ul>
          )}
          {metrics.canceled > 0 ? (
            <p className="mt-4 text-xs text-ot-muted">
              {metrics.canceled} pedido(s) cancelado(s) excluidos del total.
            </p>
          ) : null}
        </section>

        <section className="bg-white border border-black/10 p-5">
          <h2 className="font-serif text-2xl">Visitas</h2>
          {!visits ? (
            <p className="mt-4 text-sm text-ot-muted">Sin datos de visitas.</p>
          ) : (
            <>
              <div className="mt-4 grid grid-cols-3 gap-3 text-center">
                <div>
                  <p className="text-[11px] uppercase tracking-[0.12em] text-ot-muted">
                    Hoy
                  </p>
                  <p className="font-serif text-2xl mt-1">{visits.today}</p>
                </div>
                <div>
                  <p className="text-[11px] uppercase tracking-[0.12em] text-ot-muted">
                    Ayer
                  </p>
                  <p className="font-serif text-2xl mt-1">{visits.yesterday}</p>
                </div>
                <div>
                  <p className="text-[11px] uppercase tracking-[0.12em] text-ot-muted">
                    Total
                  </p>
                  <p className="font-serif text-2xl mt-1">{visits.total}</p>
                </div>
              </div>
              {visits.paths?.length ? (
                <ul className="mt-5 space-y-2 text-sm">
                  <p className="text-[11px] tracking-[0.14em] uppercase text-ot-gold">
                    Rutas top
                  </p>
                  {visits.paths.slice(0, 6).map((p) => (
                    <li key={p.path} className="flex justify-between gap-2">
                      <span className="truncate text-ot-ink/85">{p.path}</span>
                      <span className="text-ot-muted shrink-0">{p.count}</span>
                    </li>
                  ))}
                </ul>
              ) : null}
            </>
          )}
        </section>
      </div>
    </div>
  );
}
