"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Select } from "@/components/ui/select";

export function AdminScopeBar({ scopes }: { scopes: string[] }) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const selectedScopeRaw = (searchParams.get("scope") ?? "").trim().toUpperCase();
  const activeScope = scopes.includes(selectedScopeRaw) ? selectedScopeRaw : "";

  function handleScopeChange(value: string) {
    const nextScope = value.trim().toUpperCase();
    const params = new URLSearchParams(searchParams.toString());
    const targetPath = pathname || "/dashboard";

    if (nextScope) {
      params.set("scope", nextScope);
    } else {
      params.delete("scope");
    }

    if (targetPath.startsWith("/dashboard")) {
      params.delete("country");
      params.delete("month");
    }

    const query = params.toString();
    const target = query ? `${targetPath}?${query}` : targetPath;
    router.replace(target, { scroll: false });
  }

  return (
    <div className="sticky top-0 z-30 rounded-2xl border border-slate-900/20 bg-[linear-gradient(180deg,#0f172a_0%,#111e36_100%)] px-3 py-2 shadow-[0_16px_28px_-18px_rgba(2,6,23,0.9)]">
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <span className="h-2 w-2 rounded-full bg-[#F7993A] shadow-[0_0_10px_rgba(247,153,58,0.95)]" />
          <p className="caption text-[10px] uppercase tracking-[0.16em] text-blue-100/95">Admin Bar</p>
          <p className="text-sm font-semibold text-white">Dashboard Scope</p>
        </div>
        <div className="w-[220px]">
          <Select
            aria-label="Admin dashboard scope"
            value={activeScope}
            onChange={(event) => handleScopeChange(event.target.value)}
            className="h-10 rounded-xl border-[#c7d8ec] bg-white text-sm text-slate-900 shadow-[inset_0_1px_2px_rgba(15,23,42,0.03)] focus:border-[#F7993A] focus:ring-[#F7993A]/30"
          >
            <option value="">All Dashboards</option>
            {scopes.map((scope) => (
              <option key={scope} value={scope}>
                {scope}
              </option>
            ))}
          </Select>
        </div>
      </div>
    </div>
  );
}
