"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useTransition } from "react";
import { Select } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { formatCountryLabel, normalizeCountryCode } from "@/lib/countries";

type Props = {
  selected: {
    country: string;
    product: string;
    presentation: string;
    month: string;
    scope: string;
  };
  availableCountries: string[];
  availableProducts: string[];
  availableMonths: string[];
  className?: string;
};

function monthLabel(value: string) {
  return new Intl.DateTimeFormat("en-GB", { month: "long", year: "numeric" }).format(
    new Date(`${value}-01T00:00:00Z`),
  );
}

export function ClmDashboardFilters({
  selected,
  availableCountries,
  availableProducts,
  availableMonths,
  className,
}: Props) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [, startTransition] = useTransition();

  function applyFilters(next: typeof selected) {
    const params = new URLSearchParams(searchParams.toString());
    for (const [key, value] of Object.entries(next)) {
      if (value) params.set(key, value);
      else params.delete(key);
    }

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

  function resetFilters() {
    startTransition(() => {
      const query = selected.scope ? `scope=${encodeURIComponent(selected.scope)}` : "";
      router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false });
    });
  }

  return (
    <section
      className={cn(
        "enter-fade-up sticky top-0 z-20 w-full min-w-0 overflow-hidden rounded-2xl border border-[#dbe7f5]/80 bg-[linear-gradient(165deg,rgba(255,255,255,0.96)_0%,rgba(242,248,255,0.9)_100%)] px-3 py-2.5 shadow-[inset_0_1px_0_rgba(255,255,255,0.9),0_18px_30px_-24px_rgba(38,99,172,0.7)] backdrop-blur",
        className,
      )}
    >
      <div className="grid w-full min-w-0 items-end gap-2 md:grid-cols-2 xl:grid-cols-[minmax(140px,1fr)_minmax(180px,1.2fr)_minmax(160px,1fr)_auto]">
        <div>
          <label className="mb-1 flex items-center gap-1.5 px-1 caption text-[10px] uppercase tracking-[0.16em] text-slate-500">
            <span className="h-1.5 w-1.5 rounded-full bg-[#F7993A]" />
            Country
          </label>
          <Select
            aria-label="Country filter"
            value={selected.country}
            onChange={(event) =>
              applyFilters({ ...selected, country: normalizeCountryCode(event.target.value) })
            }
            className="h-12 rounded-2xl border-[#ceddee] bg-white/95 text-[15px] font-medium"
          >
            <option value="">All countries</option>
            {availableCountries.map((country) => (
              <option key={country} value={country}>
                {formatCountryLabel(country)}
              </option>
            ))}
          </Select>
        </div>

        <div>
          <label className="mb-1 flex items-center gap-1.5 px-1 caption text-[10px] uppercase tracking-[0.16em] text-slate-500">
            <span className="h-1.5 w-1.5 rounded-full bg-[#F7993A]" />
            Product
          </label>
          <Select
            aria-label="Product filter"
            value={selected.product}
            onChange={(event) => applyFilters({ ...selected, product: event.target.value })}
            className="h-12 rounded-2xl border-[#ceddee] bg-white/95 text-[14px] font-medium"
          >
            <option value="">All products</option>
            {availableProducts.map((product) => (
              <option key={product} value={product}>
                {product}
              </option>
            ))}
          </Select>
        </div>

        <div>
          <label className="mb-1 flex items-center gap-1.5 px-1 caption text-[10px] uppercase tracking-[0.16em] text-slate-500">
            <span className="h-1.5 w-1.5 rounded-full bg-[#F7993A]" />
            Month
          </label>
          <Select
            aria-label="Month filter"
            value={selected.month}
            onChange={(event) => applyFilters({ ...selected, month: event.target.value })}
            className="h-12 rounded-2xl border-[#ceddee] bg-white/95 text-[15px] font-medium"
          >
            <option value="">All months</option>
            {availableMonths.map((month) => (
              <option key={month} value={month}>
                {monthLabel(month)}
              </option>
            ))}
          </Select>
        </div>

        <div className="flex min-w-0 items-center justify-start px-1 md:col-span-2 xl:col-span-1 xl:justify-end">
          <button
            type="button"
            onClick={resetFilters}
            className="inline-flex h-9 items-center rounded-xl px-2.5 text-[15px] font-semibold text-[#2663AC] transition hover:bg-[#ecf3ff] hover:text-[#1e4f8b]"
          >
            Reset
          </button>
        </div>
      </div>
      {selected.presentation ? (
        <div className="mt-2 flex flex-wrap items-center gap-2 px-1">
          <span className="caption text-[10px] uppercase tracking-[0.16em] text-slate-500">Presentation</span>
          <span className="inline-flex max-w-full items-center rounded-full border border-[#d7e3f1] bg-[#f7fbff] px-3 py-1 text-xs font-semibold text-[#2663AC]">
            <span className="truncate">{selected.presentation}</span>
          </span>
          <button
            type="button"
            onClick={() => applyFilters({ ...selected, presentation: "" })}
            className="rounded-lg border border-[#e4eaf2] bg-white px-2.5 py-1 text-xs font-semibold text-slate-600 transition hover:bg-slate-50"
          >
            Clear presentation
          </button>
        </div>
      ) : null}
    </section>
  );
}
