"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useTransition } from "react";
import Link from "next/link";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { formatCountryLabel, normalizeCountryCode } from "@/lib/countries";
import { ALL_EMAILS_FILTER_VALUE, BRANDED_ONLY_FILTER_VALUE } from "@/lib/constants";

type Props = {
  selected: {
    from: string;
    to: string;
    country: string;
    brand: string;
    scope: string;
  };
  minDate: string;
  maxDate: string;
  availableCountries: string[];
  availableBrands: string[];
  className?: string;
};

function countryOptionLabel(code: string) {
  return formatCountryLabel(code);
}

export function DashboardFilters({
  selected,
  minDate,
  maxDate,
  availableCountries,
  availableBrands,
  className,
}: Props) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [, startTransition] = useTransition();

  function applyFilters(next: {
    from: string;
    to: string;
    country: string;
    brand: string;
    scope: string;
  }) {
    const normalized = { ...next };

    if (normalized.from && normalized.to && normalized.from > normalized.to) {
      normalized.to = normalized.from;
    }

    const params = new URLSearchParams(searchParams.toString());
    params.delete("month");
    params.delete("email");
    const entries = Object.entries(normalized) as Array<[keyof typeof normalized, string]>;
    for (const [key, value] of entries) {
      if (value) {
        params.set(key, value);
      } else {
        params.delete(key);
      }
    }

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

  const resetHref = selected.scope ? `/dashboard?scope=${selected.scope}` : "/dashboard";

  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(150px,1fr)_minmax(150px,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}>
                {countryOptionLabel(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]" />
            Brand
          </label>
          <Select
            aria-label="Brand filter"
            value={selected.brand}
            onChange={(event) => applyFilters({ ...selected, brand: event.target.value })}
            className="h-12 rounded-2xl border-[#ceddee] bg-white/95 text-[14px] font-medium"
          >
            <option value={ALL_EMAILS_FILTER_VALUE}>All brands</option>
            <option value={BRANDED_ONLY_FILTER_VALUE}>Branded only</option>
            {availableBrands.map((brand) => (
              <option key={brand} value={brand}>
                {brand}
              </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]" />
            From
          </label>
          <Input
            type="date"
            aria-label="From date filter"
            value={selected.from}
            min={minDate || undefined}
            max={selected.to || maxDate || undefined}
            onChange={(event) => applyFilters({ ...selected, from: event.target.value })}
            className="h-12 rounded-2xl border-[#ceddee] bg-white/95 text-[15px] font-medium"
          />
        </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]" />
            To
          </label>
          <Input
            type="date"
            aria-label="To date filter"
            value={selected.to}
            min={selected.from || minDate || undefined}
            max={maxDate || undefined}
            onChange={(event) => applyFilters({ ...selected, to: event.target.value })}
            className="h-12 rounded-2xl border-[#ceddee] bg-white/95 text-[15px] font-medium"
          />
        </div>

        <div className="flex min-w-0 items-center justify-start px-1 md:col-span-2 xl:col-span-1 xl:justify-end">
          <Link
            href={resetHref}
            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
          </Link>
        </div>
      </div>
    </section>
  );
}
