import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatPaise } from "@/lib/format";
import { parseDateRange, dateRangeWhere } from "@/lib/reports";
import ReportsTabs from "@/components/admin/ReportsTabs";
import ReportDateFilter from "@/components/admin/ReportDateFilter";
import ScrollableTable from "@/components/admin/ScrollableTable";

export default async function AdminProfitReportPage({
  searchParams,
}: {
  searchParams: Promise<{ from?: string; to?: string }>;
}) {
  const params = await searchParams;
  const range = parseDateRange(params);
  const createdAt = dateRangeWhere(range);

  const items = await prisma.orderItem.findMany({
    where: { order: { status: "paid", ...(createdAt ? { createdAt } : {}) } },
    include: { product: { include: { category: true } } },
  });

  type Row = { productId: string; name: string; unitsSold: number; revenue: number; knownCost: number; unitsMissingCost: number };
  const byProduct = new Map<string, Row>();
  let totalRevenue = 0;
  let totalKnownCost = 0;
  let unitsMissingCostTotal = 0;

  for (const item of items) {
    const row = byProduct.get(item.productId) ?? {
      productId: item.productId,
      name: item.product.name,
      unitsSold: 0,
      revenue: 0,
      knownCost: 0,
      unitsMissingCost: 0,
    };
    row.unitsSold += item.quantity;
    row.revenue += item.lineTotal;
    totalRevenue += item.lineTotal;
    if (item.product.purchasePrice !== null) {
      const cost = item.product.purchasePrice * item.quantity;
      row.knownCost += cost;
      totalKnownCost += cost;
    } else {
      row.unitsMissingCost += item.quantity;
      unitsMissingCostTotal += item.quantity;
    }
    byProduct.set(item.productId, row);
  }
  const rows = [...byProduct.values()].sort((a, b) => b.revenue - a.revenue);
  const knownGrossProfit = totalRevenue - totalKnownCost;

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Profit Report</h1>
      <p className="mt-1 text-sm text-stone-500">
        Gross profit computed only from products with a Purchase Price set on{" "}
        <Link href="/iv-manage-84x2/stock" className="text-rose-700 hover:underline">
          Cost &amp; Weight
        </Link>
        . Units sold without a recorded cost are shown separately, not silently counted as 100% profit.
      </p>

      <ReportsTabs active="/iv-manage-84x2/reports/profit" />
      <ReportDateFilter action="/iv-manage-84x2/reports/profit" from={range.fromStr} to={range.toStr} />

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <div className="rounded-lg border border-rose-100 bg-white p-4">
          <p className="text-xs uppercase text-stone-500">Revenue</p>
          <p className="mt-1 text-xl font-bold text-stone-800">{formatPaise(totalRevenue)}</p>
        </div>
        <div className="rounded-lg border border-rose-100 bg-white p-4">
          <p className="text-xs uppercase text-stone-500">Known cost (COGS)</p>
          <p className="mt-1 text-xl font-bold text-stone-800">{formatPaise(totalKnownCost)}</p>
        </div>
        <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-4">
          <p className="text-xs uppercase text-emerald-700">Known gross profit</p>
          <p className="mt-1 text-xl font-bold text-emerald-800">{formatPaise(knownGrossProfit)}</p>
        </div>
        <div className="rounded-lg border border-amber-200 bg-amber-50 p-4">
          <p className="text-xs uppercase text-amber-700">Units, cost unknown</p>
          <p className="mt-1 text-xl font-bold text-amber-800">{unitsMissingCostTotal}</p>
        </div>
      </div>

      {unitsMissingCostTotal > 0 && (
        <p className="mt-3 max-w-2xl rounded-md bg-amber-50 p-3 text-xs text-amber-800">
          {unitsMissingCostTotal} sold unit{unitsMissingCostTotal !== 1 ? "s" : ""} belong to products with no Purchase
          Price set — their real profit isn&apos;t in the numbers above. Set purchase prices on{" "}
          <Link href="/iv-manage-84x2/stock" className="underline">
            Cost &amp; Weight
          </Link>{" "}
          for a complete picture.
        </p>
      )}

      <div className="mt-6">
        {rows.length === 0 ? (
          <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">No paid orders in this range.</p>
        ) : (
          <ScrollableTable>
            <table className="w-full min-w-[800px] text-sm">
              <thead className="sticky top-0 z-10 bg-rose-50 text-left text-xs uppercase text-stone-500">
                <tr>
                  <th className="p-3">Product</th>
                  <th className="p-3">Units sold</th>
                  <th className="p-3">Revenue</th>
                  <th className="p-3">Known cost</th>
                  <th className="p-3">Known profit</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-rose-100">
                {rows.map((r) => (
                  <tr key={r.productId}>
                    <td className="whitespace-nowrap p-3">
                      <Link href={`/iv-manage-84x2/products/${r.productId}`} className="font-medium text-rose-700 hover:underline">
                        {r.name}
                      </Link>
                    </td>
                    <td className="whitespace-nowrap p-3 text-stone-600">{r.unitsSold}</td>
                    <td className="whitespace-nowrap p-3 text-stone-600">{formatPaise(r.revenue)}</td>
                    <td className="whitespace-nowrap p-3 text-stone-600">
                      {r.unitsMissingCost > 0 ? (
                        <span className="text-amber-700">{formatPaise(r.knownCost)} ({r.unitsMissingCost} unit{r.unitsMissingCost !== 1 ? "s" : ""} unpriced)</span>
                      ) : (
                        formatPaise(r.knownCost)
                      )}
                    </td>
                    <td className="whitespace-nowrap p-3 font-medium text-stone-800">{formatPaise(r.revenue - r.knownCost)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </ScrollableTable>
        )}
      </div>
    </div>
  );
}
