"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useTransition } from "react";

export function RevenuePeriodSwitcher({ period }: { period: number }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [pending, startTransition] = useTransition();

  function setPeriod(p: number) {
    const params = new URLSearchParams(searchParams?.toString() ?? "");
    params.set("period", String(p));
    startTransition(() => {
      router.replace(`?${params.toString()}`, { scroll: false });
      router.refresh();
    });
  }

  return (
    <div className="inline-flex rounded-full border border-border bg-background p-1">
      {[30, 90, 365].map((p) => {
        const active = p === period;
        return (
          <button
            key={p}
            type="button"
            disabled={pending}
            onClick={() => setPeriod(p)}
            className={`rounded-full px-4 py-1.5 text-xs font-semibold transition ${
              active ? "bg-[#c2410c] text-white" : "text-foreground hover:bg-muted"
            }`}
          >
            {p === 365 ? "365d" : `${p}d`}
          </button>
        );
      })}
    </div>
  );
}
