"use client";

import { Languages } from "lucide-react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";

import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";

const BULK_LANGUAGES = [
  { code: "ar", label: "Arabic" },
  { code: "dt", label: "Dutch" },
] as const;

type BulkLanguage = (typeof BULK_LANGUAGES)[number]["code"];

/**
 * Arabic / Dutch bulk-update toggles for the master lists.
 *
 * Mirrors the Yii1 links, which set `bulk_update=1&lan=ar|dt` while keeping the
 * current filtered grid. Countries and Zones shipped byte-identical copies of
 * this apart from the component name — and one of them had drifted to a hyphen
 * where the other used an em dash in the tooltip.
 */
export function MasterBulkTranslateActions() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const activeLan = searchParams.get("bulk_update") === "1" ? searchParams.get("lan") : null;

  const goBulk = (lan: BulkLanguage) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set("bulk_update", "1");
    params.set("lan", lan);
    params.set("page", "1");
    router.push(`${pathname}?${params.toString()}`);
  };

  const exitBulk = () => {
    const params = new URLSearchParams(searchParams.toString());
    params.delete("bulk_update");
    params.delete("lan");
    params.set("page", "1");
    const query = params.toString();
    router.push(query ? `${pathname}?${query}` : pathname);
  };

  return (
    <>
      {BULK_LANGUAGES.map(({ code, label }) => {
        const active = activeLan === code;
        return (
          <Tooltip key={code}>
            <TooltipTrigger asChild>
              <Button
                variant={active ? "default" : "outline"}
                size="sm"
                className="gap-1.5"
                onClick={() => (active ? exitBulk() : goBulk(code))}
              >
                <Languages className="size-4" />
                {label} bulk
              </Button>
            </TooltipTrigger>
            <TooltipContent>
              {active
                ? `Exit ${label} bulk mode (filters kept)`
                : `Bulk translate — ${label} (keeps current filters)`}
            </TooltipContent>
          </Tooltip>
        );
      })}
    </>
  );
}
