import { prisma } from "@/lib/prisma";
import { updateInvoiceSettings } from "@/lib/actions/settings";
import SettingsTabs from "@/components/admin/SettingsTabs";

export default async function AdminInvoiceSettingsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const settings = await prisma.invoiceSettings.findFirst();
  const prefix = settings?.prefix ?? "INV";
  const nextNumber = settings?.nextNumber ?? 1;
  const { error } = await searchParams;

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Invoice</h1>
      <p className="mt-1 text-sm text-stone-500">
        Every order gets a real, printable tax invoice — open any order and click &ldquo;View invoice.&rdquo; The
        number below is assigned automatically the first time an order&apos;s invoice is opened.
      </p>

      <SettingsTabs active="/iv-manage-84x2/settings/invoice" />

      {error && <p className="mb-4 mt-4 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <form action={updateInvoiceSettings} className="flex max-w-xl flex-wrap items-end gap-4 rounded-lg border border-rose-100 bg-white p-4">
        <label className="text-xs text-stone-500">
          Prefix
          <input name="prefix" defaultValue={prefix} className="mt-1 block w-28 rounded-md border border-stone-300 px-2 py-1.5 text-sm" />
        </label>
        <label className="text-xs text-stone-500">
          Next number
          <input type="number" name="nextNumber" min={1} defaultValue={nextNumber} className="mt-1 block w-28 rounded-md border border-stone-300 px-2 py-1.5 text-sm" />
        </label>
        <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800">
          Save
        </button>
      </form>
      <p className="mt-3 text-xs text-stone-400">
        Next invoice will be numbered <span className="font-mono">{prefix}-{String(nextNumber).padStart(4, "0")}</span>.
      </p>
    </div>
  );
}
