import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { updateGstSettings } from "@/lib/actions/settings";
import SettingsTabs from "@/components/admin/SettingsTabs";

export default async function AdminGstSettingsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const [tax, company] = await Promise.all([prisma.taxSettings.findFirst(), prisma.companyDetails.findFirst()]);
  const { error } = await searchParams;

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">GST</h1>
      <p className="mt-1 text-sm text-stone-500">
        This rate feeds the{" "}
        <Link href="/iv-manage-84x2/reports/tax" className="text-rose-700 hover:underline">
          Tax / GST Report
        </Link>{" "}
        and printed invoices.
      </p>

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

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

      {!company?.gstin && (
        <p className="mb-4 max-w-xl rounded-md bg-amber-50 p-3 text-sm text-amber-800">
          No GSTIN on file yet — add yours on{" "}
          <Link href="/iv-manage-84x2/settings/company" className="underline">
            Company Details
          </Link>
          .
        </p>
      )}

      <form action={updateGstSettings} 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">
          GST rate (%)
          <input
            type="number"
            name="gstRatePercent"
            min={0}
            max={50}
            defaultValue={tax?.gstRatePercent ?? 0}
            className="mt-1 block w-24 rounded-md border border-stone-300 px-2 py-1.5 text-sm"
          />
        </label>
        <label className="flex items-center gap-1.5 text-xs text-stone-500">
          <input type="checkbox" name="pricesIncludeTax" defaultChecked={tax?.pricesIncludeTax ?? true} className="h-4 w-4 rounded border-stone-300" />
          Product prices already include tax
        </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 max-w-xl text-xs text-stone-400">
        One blended rate applied to the whole order — not per-item HSN codes. If your catalog spans multiple GST
        rates, treat this as an approximation and verify with your accountant before filing.
      </p>
    </div>
  );
}
