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";

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

  const [settings, orders] = await Promise.all([
    prisma.taxSettings.findFirst(),
    prisma.order.findMany({
      where: { status: "paid", ...(createdAt ? { createdAt } : {}) },
      select: { total: true },
    }),
  ]);

  const rate = settings?.gstRatePercent ?? 0;
  const inclusive = settings?.pricesIncludeTax ?? true;
  const totalSales = orders.reduce((sum, o) => sum + o.total, 0);

  const taxableValue = rate === 0 ? totalSales : inclusive ? Math.round(totalSales / (1 + rate / 100)) : totalSales;
  const taxAmount = rate === 0 ? 0 : inclusive ? totalSales - taxableValue : Math.round(totalSales * (rate / 100));
  const grandTotal = inclusive ? totalSales : totalSales + taxAmount;

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Tax / GST Report</h1>
      <p className="mt-1 text-sm text-stone-500">
        No tax rate is stored per order today — this report reverse-calculates a split using the rate set in{" "}
        <Link href="/iv-manage-84x2/settings/gst" className="text-rose-700 hover:underline">
          Settings → GST
        </Link>
        .
      </p>

      <ReportsTabs active="/iv-manage-84x2/reports/tax" />

      <div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
        <strong>Not a substitute for GST filing.</strong> This is a simple, rate-based calculation for reference —
        it doesn&apos;t account for per-item HSN codes, mixed rates, or place-of-supply rules. Verify with your
        accountant or the GST portal before filing returns.
      </div>

      <div className="mt-4 flex max-w-xl items-center justify-between rounded-lg border border-rose-100 bg-white p-4 text-sm">
        <span className="text-stone-600">
          Current rate: <strong className="text-stone-800">{rate}%</strong> ({inclusive ? "prices include tax" : "tax added on top"})
        </span>
        <Link href="/iv-manage-84x2/settings/gst" className="font-medium text-rose-700 hover:underline">
          Edit in Settings →
        </Link>
      </div>

      <div className="mt-6">
        <ReportDateFilter action="/iv-manage-84x2/reports/tax" from={range.fromStr} to={range.toStr} />
      </div>

      {rate === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">
          Set a GST rate in Settings → GST to see a taxable value / tax split.
        </p>
      ) : (
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
          <div className="rounded-lg border border-rose-100 bg-white p-4">
            <p className="text-xs uppercase text-stone-500">Taxable value</p>
            <p className="mt-1 text-xl font-bold text-stone-800">{formatPaise(taxableValue)}</p>
          </div>
          <div className="rounded-lg border border-rose-100 bg-white p-4">
            <p className="text-xs uppercase text-stone-500">Tax ({rate}%)</p>
            <p className="mt-1 text-xl font-bold text-stone-800">{formatPaise(taxAmount)}</p>
          </div>
          <div className="rounded-lg border border-rose-100 bg-white p-4">
            <p className="text-xs uppercase text-stone-500">Grand total</p>
            <p className="mt-1 text-xl font-bold text-stone-800">{formatPaise(grandTotal)}</p>
          </div>
        </div>
      )}
      <p className="mt-3 text-xs text-stone-400">{orders.length} paid order{orders.length !== 1 ? "s" : ""} in this range.</p>
    </div>
  );
}
